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
+13.7k Golang : How to check if IP address is in range
+20.5k Golang : Use TLS version 1.2 and enforce server security configuration over client
+9.5k Golang : Fix go.exe is not compatible with the version of Windows you're running
+4.8k Unix/Linux : How to test user agents blocked successfully ?
+10.4k SSL : The certificate is not trusted because no issuer chain was provided
+21.4k Golang : simulate tail -f or read last line from log file example
+8.9k Golang : Channels and buffered channels examples
+7.3k Golang : How to check variable or object type during runtime?
+12.1k Golang : Image to ASCII art example
+18.3k Golang : Determine if directory is empty with os.File.Readdir() function
+22.1k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+11.7k Generate salted password with OpenSSL example