Imported struct method not working

go, methods, oop, struct

Solution

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.

Problem

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) } ```

Original source