Friday, April 26, 2019

Error: cannot refer to unexported name in Golang

Symptom:

  The packages are in the right place and imported ,but when we define variable from a type in another package, it error out when we define myvar a.mytype
Error: cannot refer to unexported name ******

package a
type  mytype struct {
    a int
}

package main
import "a"
func main() {
  var myvar a.mytype
}

Solution:

The reason why mytype can't be exported is due to Golang needs uppercase of first letter of a exported type or functions.  See more details in stackoverflow link

Correct one is
package a
type  Mytype struct {
    a int
}

package main
import "a"
func main() {
  var myvar a.Mytype
}

No comments: