Non-Exported Fields
This lesson covers the important concept of how to use fields of a struct if a struct is present in another file or in a separate custom package.
We'll cover the following...
Methods and non-exported fields
How can we change, or even read the name of the object of a user-defined type in another program? This is accomplished using a well-known technique from OO-languages: provide getter and setter methods. For the setter-method, we use the prefix Set, and for the getter-method, we only use the field name.
Look at the example below:
package main import ( "fmt" "person" ) func main() { p := new(person.Person) // error: p.firstName undefined // (cannot refer to unexported field or method firstName) //p.firstName = "Eric" p.SetFirstName("Eric") fmt.Println(p.FirstName()) // Output: Eric }
See the person.go file. We have a struct of type Person
with two string fields firstName
and lastName
at line 3.
Look at ...