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
+8.3k Facebook : Getting the friends list with PHP return JSON format
+6k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+32.4k Golang : Call a function after some delay(time.Sleep and Tick)
+2.6k Java : Get FX sentiment from website example
+5.1k Golang : Process non-XML/JSON formatted ASCII text file example
+12.6k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+9.5k Golang : Bubble sort example
+8.5k Golang : Resumable upload to Google Drive(RESTful) example
+5.1k Golang : Detect face in uploaded photo like GPlus
+4.9k Java : Human readable password generator
+7.7k Golang : Find duplicate files with filepath.Walk