函数/结构体/接口名称中允许使用哪些字符?

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

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 &quot;fmt&quot;

type sel struct {
    s string
}

func _(s string) sel {
    return sel{s}
}

func main() {
    fmt.Println(&quot;Hello&quot;)
    _(&quot;foo&quot;) // &lt;-- does not compile
}

If I comment the entire _(&quot;foo&quot;) 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_letterunicode_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.

huangapple
  • 本文由 发表于 2012年7月27日 22:07:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/11689485.html
匿名

发表评论

匿名网友

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

确定