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
+10.2k Golang : Use regular expression to get all upper case or lower case characters example
+13.1k Golang : List objects in AWS S3 bucket
+23.7k Find and replace a character in a string in Go
+11.1k Golang : Roll the dice example
+8k Golang : What fmt.Println() can do and println() cannot do
+7.1k Nginx : How to block user agent ?
+14.4k Golang : Parsing or breaking down URL
+7.7k Gogland : Where to put source code files in package directory for rookie
+8.7k Golang : Find duplicate files with filepath.Walk
+15k Golang : Search folders for file recursively with wildcard support
+9.5k Mac OSX : Get a process/daemon status information
+7.1k Javascript : How to get JSON data from another website with JQuery or Ajax ?