Sorry for the basic question. I am new to GoLang.
I have a custom type named ProtectedCustomType
and I don't want the variables within that to be set
directly by the caller, rather want a Getter
/ Setter
methods to do that
Below is my ProtectedCustomType
package custom
type ProtectedCustomType struct {
name string
age int
phoneNumber int
}
func SetAge (pct *ProtectedCustomType, age int) {
pct.age=age
}
And here is my main
function
import (
"fmt"
"./custom"
)
var print =fmt.Println
func structCheck2() {
pct := ProtectedCustomType{}
custom.SetAge(pct,23)
print (pct.Name)
}
func main() {
//structCheck()
structCheck2()
}
But i couldn't proceed further .. can you please help me on how to achieve getter-setter concept in GoLang ?
If you want to have setter you should use method declaration:
func(pct *ProtectedCustomType) SetAge (age int) {
pct.age = age
}
and then you will be able to use:
pct.SetAge(23)
This kind of declarations enables you to execute function on your structure, by using
(pct *ProtectedCustomType)
Your are passing pointer to your struct so operations on it changes its internal representation.
You can read more about this kind of function under this link, or under official documentation.