Friday 15 March 2013

Should I create pointers on struct field or on struct? Go -



Should I create pointers on struct field or on struct? Go -

i'm wondering what's best practice on pointers. should define them on struct or on fields. though makes sense define pointer struct here illustration find intriguing. if fields pointers why shouldn't utilize pointer entire struct instead address each field?

type tag struct { tag *string `json:"tag,omitempty"` sha *string `json:"sha,omitempty"` url *string `json:"url,omitempty"` message *string `json:"message,omitempty"` tagger *commitauthor `json:"tagger,omitempty"` object *gitobject `json:"object,omitempty"` }

a sample of struct content below

{ "tag": "v0.0.1", "sha": "940bd336248efae0f9ee5bc7b2d5c985887b16ac", "url": "https://api.github.com/repos/octocat/hello-world/git/tags/940bd336248efae0f9ee5bc7b2d5c985887b16ac", "message": "initial version\n", "tagger": { "name": "scott chacon", "email": "schacon@gmail.com", "date": "2011-06-17t14:53:35-07:00" }, "object": { "type": "commit", "sha": "c3d0be41ecbe669545ee3e94d31ed9a4bc91ee3c", "url": "https://api.github.com/repos/octocat/hello-world/git/commits/c3d0be41ecbe669545ee3e94d31ed9a4bc91ee3c" } }

it is more efficient have non-pointer fields, in case have odd reason utilize pointers, discussed @ the blog post "go, rest apis, , pointers".

it looks struct you're talking defined here, in go-github library. makes every field pointer it's trivial pass nil subset of fields (just don't specify them). way when you're constructing, say, patch phone call update via github api, can specify whether description not relevant request (you're not updating description) or whether intend set description "". key thing "" , nil have different meanings in patch calls api.

if have similar want distinguish 0 string/struct/etc. "not applicable object", can utilize pointers. if don't need that, though, it's improve not create every field pointer, because tend create memory usage patterns worse--little more ram taken up, more cache misses, more stuff gc needs trace through, etc. approach doesn't add together layer of pointer indirection (but looks tiny bit more verbose when writing code) sql.nullstring, struct bool , string.

in github's case, performance impact of isn't huge deal--the time github takes respond web request going dwarf cpu-bound work library anyway.

pointers struct go

No comments:

Post a Comment