go - 何时使用 var 或 := in Go?

标签 go

这个问题在这里已经有了答案:





Why there are two ways of declaring variables in Go, what's the difference and which to use?

(1 个回答)



var vs := in Go

(3 个回答)


2年前关闭。




下面两个例子有什么区别吗?

type Example struct {}

func main() {
  e := Example{}
}

对比
type Example struct {}

func main() {
  var e Example
}

有更好的吗?

谢谢!

最佳答案

可能值得注意:
使用 :=当您需要创建一个带有特定值(不是零值)的变量时。

number := 12
obj := SomeStruct{name: "user"}
slice := []string{"a", "b", "c"}
someNilPointerData := (*SomeStruct)(nil)

使用 var当您需要在没有任何初始化的情况下定义变量时使用关键字,因此将在其上使用零值。
var a int // zero value of int is 0
var mut sync.Mutex
var result []map[string]interface{}

使用 var 的另一个好处关键字,在单个语句中创建多个相同类型的变量。
var result1, result2, result3, result4 []map[string]interface{}
var关键字对于将某些文字值存储在具有不同数据类型的变量中也很有用。
// store string literal value in interface{} variable
var anyValue interface{} = "hello world"

// store int literal value in float64 variable
var otherValue float64 = 12

关于go - 何时使用 var 或 := in Go?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53404305/

相关文章:

去测试 foo - 找不到包 foo

go - 在Go应用程序中使用Cassandra插入之前检查行是否存在

arrays - 在 Go 中,如何将 [16]float32 转换为 *float32

Golang 位只使用无符号?

go - 编辑多个未发布的 Go 模块的本地副本

go - 相同依赖的两个版本 - 较低版本被忽略

mongodb - 使用 FindOne 和 $natural 从 GoLang 中的 mongodb 获取最后插入的元素

go - 安装 Go from source to custom prefix

mysql - Docker mysql 数据不反射(reflect)变化

git - 如何在 git2go (libgit2) 中列出包含给定提交的分支?