This error occurs because Go's visibility rules prevent code outside a package from accessing fields or methods that start with a lowercase letter. To fix it, you must either rename the identifier to start with an uppercase letter to export it, or provide a public getter/setter method if you need to maintain encapsulation.
If you need the field accessible from other packages, simply capitalize the first letter of the field name. This makes it exported and visible to any code that imports the package.
// Before (unexported, causes error if accessed from other package)
type User struct {
id int
}
// After (exported, accessible)
type User struct {
ID int
}
// Usage in another package
func main() {
u := User{ID: 101}
fmt.Println(u.ID) // Works
}
If you want to keep the field private (lowercase) to enforce encapsulation but still allow external access, define exported methods to get or set the value. This is the idiomatic Go approach for managing internal state.
type User struct {
id int
}
// Exported getter method
func (u *User) GetID() int {
return u.id
}
// Exported setter method
func (u *User) SetID(id int) {
u.id = id
}
// Usage in another package
func main() {
u := &User{}
u.SetID(101)
fmt.Println(u.GetID()) // Works without exposing 'id' directly
}
Remember that this rule applies to methods as well. If you define a method like func (u *User) validate(), it is unexported and cannot be called from outside the package. Rename it to Validate() to make it public. If the error persists despite capitalization, verify that the code attempting the access is actually in a different package; code within the same package can always access unexported members.