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
+16.2k Golang : Linked list example
+14k Golang : Get timezone offset from date or timestamp
+20.2k SSL : How to check if current certificate is sha1 or sha2
+4.1k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+3.9k Unix/Linux : How to pipe/save output of a command to file?
+7.6k Android Studio : Indicate progression with ProgressBar example
+12.6k Golang : Gin framework accept query string by post request example
+14.1k Golang : Validate hostname
+26.8k Golang : Connect to database (MySQL/MariaDB) server
+7.1k Golang : Variadic function arguments sanity check example
+10.4k SSL : The certificate is not trusted because no issuer chain was provided
+7.9k Golang : Find the length of big.Int variable example