gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:48:49 25 4
gpt4 key购买 nike

Golang 中有一些变量:

  1. 全局变量:var a int
  2. 局部变量:func hello() { var a int }
  3. 返回变量:func hello() (a int) {}

Golang 有时会自动初始化一些变量,
但我不知道什么时候以及为什么?这让我很困惑。

例子:

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
}

我应该在使用前初始化哪一个?

最佳答案

Golang 会初始化所有变量(不是 sometimes ,不是 some ):

在您的代码中:

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

你传递了一个 nil 指针,但你需要一个 a 指向的值,而不是一个 nil 指针:
因此,您可以创建一个值,然后将此值的地址存储在 a 中:


当您使用 var a *Userfunc bar(bts []byte) (a *User) 时:
a 是指向 User 类型的指针,它被初始化为零值,即 nil,
参见 ( The Go Playground ):

package main

import "fmt"

func main() {
var a *User
fmt.Printf("%#v\n\n", a)
}

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

输出:

(*main.User)(nil)

并且您可以使用 a = &User{} 来初始化它,就像这个工作代码 ( 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\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"`
}

输出:

&main.User{Name:"Alex", Age:3}

&main.User{Name:"Alex", Age:3}

Variable declarations :

A variable declaration creates one or more variables, bindscorresponding identifiers to them, and gives each a type and aninitial value.

The initial value (zero value) :

When storage is allocated for a variable, either through a declarationor a call of new, or when a new value is created, either through acomposite literal or a call of make, and no explicit initialization isprovided, the variable or value is given a default value. Each elementof 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, andmaps. This initialization is done recursively, so for instance eachelement of an array of structs will have its fields zeroed if no valueis specified.

并查看 func Unmarshal(data []byte, v interface{}) error 文档:

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

关于variables - 我应该什么时候初始化 Golang 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39113464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com