误解了Go语言中 := 的用法

huangapple go评论90阅读模式
英文:

Misunderstanding the usage of := in Go

问题

我正在阅读这个文档,看到以下片段:

> := 语法是声明和初始化变量的简写形式,例如在这种情况下 var f string = "short"。

f := "short"
fmt.Println(f)

我的问题是:它只适用于字符串吗?还是足够动态,可以理解应该存储的数据类型?

另外:它和 var f = "short" 是一样的吗?

英文:

I was reading this doc and saw the following fragment:

> The := syntax is shorthand for declaring and initializing a variable, e.g. for var f string = "short" in this case.

f := "short"
fmt.Println(f)

The point is: is it only for strings? Or is it dymanic enough to understand what datatype should it store?

And plus: isn't it the same of var f = "short"?

答案1

得分: 5

当然,它推断出右侧表达式返回的明显类型。

规范给出了以下示例:

i, j := 0, 10
f := func() int { return 7 }
ch := make(chan int)
r, w := os.Pipe(fd)  // os.Pipe()返回两个值
_, y, _ := coord(p)  // coord()返回三个值;只对y坐标感兴趣

请注意,这不是动态的:所有操作都发生在编译时,类型由右侧表达式给出。

英文:

Of course it infers the obvious type(s) returned by the expression on the right side.

The specification gives those examples :

i, j := 0, 10
f := func() int { return 7 }
ch := make(chan int)
r, w := os.Pipe(fd)  // os.Pipe() returns two values
_, y, _ := coord(p)  // coord() returns three values; only interested in y coordinate

Note that it's not dynamic : everything happens at compile time, the type(s) being given by the right part expression.

huangapple
  • 本文由 发表于 2014年12月18日 00:43:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/27530523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定