3 ms·
Another approach is sql.NullString and related types from database/sql: http://golang.org/pkg/database/sql/#NullString http://golang.org/pkg/database/sql/#NullS
by staunch 12y ago
Another approach is sql.NullString and related types from database/sql: http://golang.org/pkg/database/sql/#NullString http://golang.org/pkg/database/sql/#NullString
foo := sql.NullString{"bar",true}
if foo.Valid {
fmt.Println(foo.String)
}
- mitchellh 12y agoYes, but the blog post makes it pretty clear that easy JSON decoding/encoding is a primary goal, and this is not friendly to that.
- deleted 12y ago[deleted]
- deleted 12y ago[deleted]
- deleted 12y ago[deleted]
- staunch 12y agofunc (ns NullString) MarshalJSON() ([]byte, error) { if !ns.Valid { return []byte("null"), nil } return json.Marshal(ns.String) } It would render `user_id: null` instead of `user_id: ""` which should work, I think.
- willnorris 12y agosure it's valid JSON, but it really depends on the API as to whether it handles null values properly when it's expecting some other type. I honestly haven't tried that with the GitHub API, but based on what I've seen it probably handles it fine. Others may not.
- deleted 12y ago[deleted]
- kyrra 12y agoAnd this is the problem about using null as a valid state for data. In many languages, using null as a valid data value just can cause all kinds of problem (extra checks, not supported, or problems accessing null data).
- troyk 12y agoSeems like the issue is trying to keep type safety when doing a PATCH so instead of polluting the struct with pointers so it can be used to do a PATCH, why not create a separate type specific to that purpose: type Repository struct { Name string `json:"name"` Description string `json:"description"` Private bool `json:"private"` } // response to blog post https://willnorris.com/2014/05/go-rest-apis-and-pointers type RepositoryPatch struct { Repository patched_fields []string } func (rp *RepositoryPatch) SetPrivate(private bool) { rp.patch_fields = append(rp.patch_fields,"private") rp.Private = private } func (rp *RepositoryPatch) MarshalJSON() ([]byte, error) { // marshal rp to []byte then unmarshal to map[string]interface{} // filter patched_fields and then marshal again // ;) }
- willnorris 12y agoyeah, that's similar to the field mask that was discussed on the issue (https://github.com/google/go-github/issues/19#issuecomment-22151321 https://github.com/google/go-github/issues/19#issuecomment-2...), though your approach does provide some nice encapsulation. Given how large some of the GitHub data types are, you'd probably want to auto-generate the setter methods, similar to what goprotobuf does for accessor methods.