Imported struct method not working

Viewed 1933

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)
}
2 Answers
Related