If I run the following code everything compiles and runs fine:
package main
import "fmt"
type Point struct {
x, y int
}
func (p *Point) init() bool {
p.x = 5
p.y = 10
return true
}
func main() {
point := Point{}
point.init()
fmt.Println(point)
}
But when I move the Point struct
to a package in the $GOPATH
directory then I get the following error: point.init undefined (cannot refer to unexported field or method class.(*Point)."".init)
Can anyone explain to me why this happens?
Once I put the Point struct
in a package called class
the code looks as follows (the error is on the 8th line where I call the init
method):
package main
import "fmt"
import "class"
func main() {
point := class.Point{}
point.init()
fmt.Println(point)
}
Rename init() to Init() should work!
Basically, all the things(function, method, struct, variable) that not start with an Unicode upper case letter will just visible inside their package!
You need to read more from the language spec here: http://golang.org/ref/spec#Exported_identifiers
Relevant bit:
An identifier may be exported to permit access to it from another package. An identifier is exported if both:
- the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
- the identifier is declared in the package block or it is a field name or method name. All other identifiers are not exported.
Only functions/methods that have the first letter of their name capitalized are exported
http://golang.org/doc/effective_go.html#commentary
Every exported (capitalized) name in a program...
When I changed init
to Init
everything worked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With