dongse7261
2016-08-24 02:25
浏览 53
已采纳

什么时候应该初始化Golang变量

There are some kind of variables in Golang:

  1. global variable: var a int
  2. local variable: func hello() { var a int }
  3. return variable: func hello() (a int) {}

Golang sometimes will auto-init some variables,
but I don't know when and why? It confused me.

Example:

type User struct {
  Name string `json:"name"`
  Age  int    `json:"age"`
}

func foo(bts []byte) {
  var a User
  err := json.Unmarshal(bts, &a)  // It's ok
}

func bar(bts []byte) (a *User) {
  err := json.Unmarshal(bts, a) // It will crash
}

which one should I have to initialize before use?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题