Assigning null to JSON fields instead of empty strings

后端 未结 5 1903
迷失自我
迷失自我 2020-11-29 23:34

Since empty string is the zero/default value for Go string, I decided to define all such fields as interface{} instead. for example



        
5条回答
  •  执笔经年
    2020-11-30 00:27

    You could use something like sql.NullString,use 'Valid' to check if it is a nil value.

    NullString represents a string that may be null. NullString implements the Scanner interface so it can be used as a scan destination:

    type NullString struct {
        String string
        Valid  bool // Valid is true if String is not NULL
    }
    
    var s NullString
    err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
    ...
    if s.Valid {
       // use s.String
    } else {
       // NULL value
    }
    

    Please DO NOT use pointers like below:

    type student struct {
      FirstName  *string `json:"first_name"`
      MiddleName *string `json:"middle_name"`
      LastName   *string `json:"last_name"`
    }
    

    Because you need check nil value and dereference like below everywhere,and maybe cause unexpected crash somewhere:

    if obj.FirstName != nil {
       fmt.Print("%s", *obj.FirstName)
    }
    

    I have compared two solution and choosed former method in my extensively production code,it work ok.

提交回复
热议问题