Reputation: 21111
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?
Upvotes: 2
Views: 2815
Reputation: 16420
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.
Upvotes: 6
Reputation: 54107
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.
Upvotes: 10