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("[email protected]")
employee.Name = "Adam"
fmt.Println(employee)
// Retrieve data from private variables via GetEmail method
fmt.Println(employee.GetEmail())
fmt.Println(employee.Name)
}
Output :
{ }
{Adam [email protected]}
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
+35k Golang : Strip slashes from string example
+4.2k Linux/MacOSX : Search and delete files by extension
+7.1k Golang : Word limiter example
+5.7k Golang : Detect variable or constant type
+27.1k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+4.7k Google : Block or disable caching of your website content
+22.7k Golang : Randomly pick an item from a slice/array example
+4.6k Python : Find out the variable type and determine the type with simple test
+5.2k How to check with curl if my website or the asset is gzipped ?
+24.9k Golang : convert rune to integer value
+41k Golang : How do I convert int to uint8?
+24.7k Golang : Generate MD5 checksum of a file