英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论