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条回答 默认 最新

  • duanla1996 2016-08-24 03:35
    关注

    Golang will init all variables (not sometimes, not some):

    In your code:

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

    You passed a nil pointer but you need a value pointed to by a , not a nil pointer:
    So you may create a Value then store the address of this Value inside a:


    When you use var a *User or func bar(bts []byte) (a *User):
    The a is a pointer to the User type, and it is initialized to it's zero value, which is nil,
    see (The Go Playground):

    package main
    
    import "fmt"
    
    func main() {
        var a *User
        fmt.Printf("%#v
    
    ", a)    
    }
    
    type User struct {
        Name string `json:"Name"`
        Age  int    `json:"Age"`
    }
    

    output:

    (*main.User)(nil)
    

    And You may use a = &User{} to initialize it, like this working code (The Go Playground):

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func foo(bts []byte) (*User, error) {
        var a User
        err := json.Unmarshal(bts, &a) // It's ok
        return &a, err
    }
    
    func bar(bts []byte) (a *User, err error) {
        a = &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
    
    ", u) // &main.User{Name:"Alex", Age:3}
    
        u, err = bar([]byte(str))
        if err != nil {
            panic(err)
        }
        fmt.Printf("%#v
    
    ", 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}
    

    Variable declarations:

    A variable declaration creates one or more variables, binds corresponding identifiers to them, and gives each a type and an initial value.

    The initial value (zero value):

    When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type: false for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.

    And see func Unmarshal(data []byte, v interface{}) error Docs:

    Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。
  • ¥15 SQL Server analysis services 服务安装失败