dttvb115151 2016-04-24 07:33
浏览 143
已采纳

如何在Go中安全地检测struct的零值?

I tried to written an simple ORM for MySQL, I got a problem, if a defined struct missing some field:

type User struct {
    ID        int64
    Username  string
    Password  string
    Email     string
    Comment   string
}

var u = User{Username: "user_0001", Password: "password"}

Some fields of User didn't given a value, then it's value will be a zeroed value, such as string "", bool false, integer 0 and so on.

So I am using reflect to get field name and value, generate a sql to insert row.

INSERT INTO User (Id, Username, Password, Email, Comment) Values (0, "user_0001", "password", , ,)

You can see there has some zeroed value of string, if I detect empty string "" and skip them, I may skip normal value.

  • 写回答

2条回答 默认 最新

  • douju7765 2016-04-24 15:35
    关注

    To handle database columns that may be NULL, you can either use pointers as Friedrich Große suggests, or use the Null...-variants found in the db package, for instance sql.NullString.

    To use the Null-variants, the struct would be

    type User struct {
        ID        int64
        Username  string
        Password  string
        Email     sql.NullString
        Comment   sql.NullString
    }
    

    You can then detect of a value is set by checking NullString.Valid. The downside of using NullString is that you have to add special cases when printing or marshaling them, as they don't implement the Stringer interface, nor MarshalJSON or UnmarshalJSON. You also have to remember to set NullString.Valid manually when setting the value of the string.

    For instance, a test like

    func TestNullString(t *testing.T) {
        s := sql.NullString{}
        t.Log(s)
    
        s.String = "Test"
        s.Valid = true
        t.Log(s)
    }
    

    Prints

    null_string_test.go:21: { false}
    null_string_test.go:25: {Test true}
    

    To print a NullString you have to instead do

    func TestNullString(t *testing.T) {
        s := sql.NullString{}
        t.Log(s.String)
    
        s.String = "Test"
        s.Value = true
        t.Log(s.String)
    }
    

    Which prints:

    null_string_test.go:21: 
    null_string_test.go:25: Test
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路