After creating a struct like this:
type Foo struct {
name string
}
func (f Foo) SetName(name string){
f.name=name
}
func (f Foo) GetName string (){
return f.name
}
How do I create a new instance of Foo and set and get the name? I tried the following:
p:=new(Foo)
p.SetName("Abc")
name:=p.GetName()
fmt.Println(name)
Nothing gets printed, because name is empty. So how do I set and get a field inside a struct?
Commentary (and working) example:
Test it and take A Tour of Go to learn more about methods and pointers, and the basics of Go at all.
For example,
Output:
Setters and getters are not that idiomatic to Go. Especially the getter for a field x is not named GetX but just X. See http://golang.org/doc/effective_go.html#Getters
If the setter does not provide special logic, e.g. validation logic, there is nothing wrong with exporting the field and neither providing a setter nor a getter method. (This just feels wrong for someone with a Java background. But it is not.)