Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imported struct method not working

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)
}
like image 334
Tom Avatar asked Dec 05 '22 08:12

Tom


2 Answers

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:

  1. the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
  2. the identifier is declared in the package block or it is a field name or method name. All other identifiers are not exported.
like image 99
nvcnvn Avatar answered Jan 05 '23 22:01

nvcnvn


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.

like image 25
Tom Avatar answered Jan 05 '23 21:01

Tom