Golang : Implement getters and setters
Because Golang does not provide automatic getters and setters, Go programmers will have to implement the getters and setters themselves. This is a quick tutorial on how to set and get identifiers value in a struct.
package main
import (
"fmt"
)
type Person struct {
Name string // exported identifier
email string // un-exported identifier... need Set and Get methods for help
}
func (p *Person) SetEmail(email string) {
p.email = email
}
func (p Person) GetEmail() string {
return p.email
}
func main() {
employee := Person{}
//employee := new(Person) // new object
fmt.Println(employee)
// set data to private variable via SetEmail method
employee.SetEmail("happyworker@xmail.com")
employee.Name = "Adam"
fmt.Println(employee)
// Retrieve data from private variables via GetEmail method
fmt.Println(employee.GetEmail())
fmt.Println(employee.Name)
}
Output :
{ }
{Adam happyworker@xmail.com}
happyworker@xmail.com
Adam
References :
http://golang.org/doc/effective_go.html#Getters
https://www.socketloop.com/tutorials/golang-dealing-with-struct-s-private-part
See also : Golang : Set or Add HTTP Request Headers
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+3.6k Golang : Switch Redis database redis.NewClient
+11.2k Golang : How to flush a channel before the end of program?
+18.7k Golang : How to make function callback or pass value from function as parameter?
+11.8k Golang : Determine if time variables have same calendar day
+11.1k Golang : Intercept and process UNIX signals example
+11.8k Golang : Convert decimal number(integer) to IPv4 address
+13.9k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+5.3k Golang : What is StructTag and how to get StructTag's value?
+7k Golang : Transform lisp or spinal case to Pascal case example
+17.3k Golang : Multi threading or run two processes or more example
+13.5k Golang : Activate web camera and broadcast out base64 encoded images
+11k Golang : Web routing/multiplex example