gpt4 book ai didi

go - 在 Go 中声明变量

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

Go 文档指出应该使用速记:

x := "Hello World" 

相对于长格式

var x string = "Hello World"

提高可读性。虽然以下工作:

package main   
import "fmt"
var x string = "Hello World"
func main() {
fmt.Println(x)
}

这不是:

package main
import "fmt"
x := "Hello World"
func main() {
fmt.Println(x)
}

并给出错误“函数体之外的非声明语句”。相反,如果我在函数中声明它:

package main
import "fmt"
func main() {
x := "Hello World"
fmt.Println(x)
}

然后它就可以正常工作了。看来我只能在使用变量的函数中使用速记。是这样吗?谁能告诉我为什么?

最佳答案

规范指出short variable declarations can only be used in functions .

有了这个限制,包级别的所有内容都以关键字开头。这simpflies parsing .

关于go - 在 Go 中声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26388402/

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