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
+6.1k Golang : Accessing dataframe-go element by row, column and name example
+5.2k PageSpeed : Clear or flush cache on web server
+10.9k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+6.9k Golang : Load DSA public key from file example
+8.9k Golang : Edge detection with Sobel method
+13.8k Golang : Basic authentication with .htpasswd file
+21k Golang : Repeat a character by multiple of x factor
+13.6k Golang : Accurate and reliable decimal calculations
+14.3k Golang : invalid character ',' looking for beginning of value
+7k Golang : Append and add item in slice
+8.1k Golang : Timeout example
+8.2k Golang : does not implement flag.Value (missing Set method)