Encapsulation prevents internal attribute values from being accessed directly from the outside and protects internal values by allowing access only through exposed methods (e.g. getter, setter). In other words, it hides the internal implementation and stores only valid values through data checking.
Let's write how to create getter and setter methods in Go using the Person struct below.
name, ageare lowercase, so they cannot be accessed from the outside
type Person struct {
name string
age int
}
Setter
- A
Settercan be created asSetFoo()- To call the method from the outside, the first letter of the method is uppercase
- In a
Setter, the receiver argument needs to be aPointer receiver- This is because it must return the changed value after the method executes
- In a
Setter, you can add data validation logic to check validity
func (p *Person) SetName(name string) error {
if name == "" {
return errors.New("invalid name")
}
p.name = name
return nil
}
The SetName setter method takes name as an argument and stores the value in the name field of the Person struct. If name is empty, it returns an Error.
Getter
- A
Getteris named with just the variable name, without prefixing it with Get- e.g.
GetName()- X - e.g.
Name()- O - Even if you write the code with
GetName(), it works fine, but by Go convention,getis not used
- e.g.
func (p Person) Name() string {
return p.name
}
A
Getterreturns only a value, so it doesn't need a pointer receiver argument. However, for consistency, it's good to declare it with a pointer receiver.
func (p *Person) Name() string {
return p.name
}
The code written in this post can be found on github.