Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which characters are allowed in a function/struct/interface name?

Tags:

go

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?

like image 817
Emil H Avatar asked May 13 '26 00:05

Emil H


1 Answers

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.

like image 65
Nick Craig-Wood Avatar answered May 14 '26 15:05

Nick Craig-Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!