go - When should I initialize Golang variables -
there kind of variables in golang:
- global variable:
var int
- local variable:
func hello() { var int }
- return variable:
func hello() (a int) {}
golang auto-init variables,
don't know when , why? confused me.
example:
type user struct { name string `json:"name"` age int `json:"age"` } func foo(bts []byte) { var user err := json.unmarshal(bts, &a) // it's ok } func bar(bts []byte) (a *user) { err := json.unmarshal(bts, a) // crash }
which 1 should have initialize before use?
golang init variables (not sometimes, not some):
in code:
func bar(bts []byte) (a *user) { err := json.unmarshal(bts, a) // crash }
you passed nil pointer need value pointed a
, not nil pointer:
may create value store address of value inside a
:
when use var *user
or func bar(bts []byte) (a *user)
:
a
pointer user
type, , initialized it's 0 value, nil
,
see (the go playground):
package main import "fmt" func main() { var *user fmt.printf("%#v\n\n", a) } type user struct { name string `json:"name"` age int `json:"age"` }
output:
(*main.user)(nil)
and may use a = &user{}
initialize it, working code (the go playground):
package main import ( "encoding/json" "fmt" ) func foo(bts []byte) (*user, error) { var user err := json.unmarshal(bts, &a) // it's ok return &a, err } func bar(bts []byte) (a *user, err error) { = &user{} err = json.unmarshal(bts, a) // it's ok return } func main() { str := `{ "name": "alex", "age": 3 }` u, err := foo([]byte(str)) if err != nil { panic(err) } fmt.printf("%#v\n\n", u) // &main.user{name:"alex", age:3} u, err = bar([]byte(str)) if err != nil { panic(err) } fmt.printf("%#v\n\n", u) // &main.user{name:"alex", age:3} } type user struct { name string `json:"name"` age int `json:"age"` }
output:
&main.user{name:"alex", age:3} &main.user{name:"alex", age:3}
a variable declaration creates 1 or more variables, binds corresponding identifiers them, and gives each type , initial value.
the initial value (zero value):
when storage allocated variable, either through declaration or call of new, or when new value created, either through composite literal or call of make, , no explicit initialization provided, variable or value given default value. each element of such variable or value set 0 value type:
false
booleans,0
integers,0.0
floats,""
strings, andnil
pointers, functions, interfaces, slices, channels, , maps. initialization done recursively, instance each element of array of structs have fields zeroed if no value specified.
and see func unmarshal(data []byte, v interface{}) error
docs:
unmarshal parses json-encoded data , stores result in value pointed v.
Comments
Post a Comment