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
+22.4k Golang : Strings to lowercase and uppercase example
+9.7k Golang : Translate language with language package example
+5.5k Get website traffic ranking with Similar Web or Alexa
+5.3k PHP : Fix Call to undefined function curl_init() error
+4.5k MariaDB/MySQL : Form select statement or search query with Chinese characters
+8.4k Golang : How to join strings?
+20.4k PHP : Convert(cast) int to double/float
+27k Golang : Convert CSV data to JSON format and save to file
+10.8k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+9.1k Mac OSX : Get a process/daemon status information
+13.1k Golang : Generate Code128 barcode
+8.5k Android Studio : Image button and button example