英文:
Which characters are allowed in a function/struct/interface name?
问题
我是新手学习Go语言,并开始尝试使用A Tour of Go。我注意到一个奇怪的地方,就是我可以给一个函数命名为_
,但是这个函数不能被调用:
import "fmt"
type sel struct {
s string
}
func _(s string) sel {
return sel{s}
}
func main() {
fmt.Println("Hello")
_("foo") // <-- 无法编译通过
}
如果我注释掉整个_("foo")
这一行,程序就可以编译通过。
我的问题是函数名允许使用哪些字符?只能使用字母和数字字符,还是可以使用$
等字符?
命名其他东西(如结构体、接口等)的规则与函数相同吗?
英文:
I am new to go and have started playing around with A Tour of Go. I noticed one peculiarity namely that I am allowed to name a function _
but that function can not be called:
import "fmt"
type sel struct {
s string
}
func _(s string) sel {
return sel{s}
}
func main() {
fmt.Println("Hello")
_("foo") // <-- does not compile
}
If I comment the entire _("foo")
line then the program compiles.
My question is what characters are allowed in function names? Is it only alphanumeric characters or can I use $
for instance?
Are the rules for naming other things e.g. structs, interfaces etc. the same as those for functions?
答案1
得分: 10
从规范中可以看到:
> 下划线字符_代表空白标识符,可以像其他标识符一样在声明中使用,但该声明不会引入新的绑定。
这就解释了为什么代码是有效的,但你不能调用名为_
的函数。
在Go中,当你想要赋值一个变量但忽略它时,可以使用_
。调用一个名为_
的函数也是一样的 - 你定义了它,但编译器会忽略它。
英文:
From the spec
> The blank identifier, represented by the underscore character _, may
> be used in a declaration like any other identifier but the declaration
> does not introduce a new binding.
Which explains why the code was valid but you couldn't call the function called _
_
is used in Go when you want to assign a variable but ignore it. Calling a function _ does just the same - you defined it but the compiler will ignore it.
答案2
得分: 6
规范1指出,函数、变量或常量的名称必须以(unicode_letter
或_
)开头,并且可以以任何(unicode_letter
、unicode_digit
或_
)结尾。
如果您愿意,unicode_letter
可以是中文或希伯来字母。
英文:
The spec says that func, var or const name must begin with (unicode_letter
or _
), and can end with any (unicode_letter
, unicode_digit
or _
).
unicode_letter
can be a Chinese, or Hebrew letter if you'd like it to.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论