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
+24.5k Golang : Change file read or write permission example
+10.1k Golang : Test a slice of integers for odd and even numbers
+18.6k Golang : Send email with attachment
+8k Javascript : Put image into Chrome browser's console
+7.9k Golang : Example of how to detect which type of script a word belongs to
+15.8k Golang : ROT47 (Caesar cipher by 47 characters) example
+30.4k Golang : How to verify uploaded file is image or allowed file types
+6.2k Golang : Grab news article text and use NLP to get each paragraph's sentences
+10k CodeIgniter : Load different view for mobile devices
+7k Golang : Fibonacci number generator examples
+11.2k Google Maps URL parameters configuration
+8.1k Golang : Append and add item in slice