Skip to content

Instantly share code, notes, and snippets.

@hazbo
Last active December 30, 2015 00:19
Show Gist options
  • Save hazbo/7748238 to your computer and use it in GitHub Desktop.
Save hazbo/7748238 to your computer and use it in GitHub Desktop.
Basic structure with setters and getters in Go.
package main
import(
"fmt"
)
// Defining the data types we will use
// in our Person struct
type Person struct {
name string
age int
}
// Using a pointer as the setter will modify
// the name
func (p *Person) SetName(name string) {
p.name = name
}
func (p *Person) SetAge(age int) {
p.age = age
}
// No pointer here as we will just be accessing
// the name without modification
// Name is the idiomatic name for the getter as appose
// to GetName (golang.org/doc/effective_go.html#Getters)
func (p Person) Name() string {
return p.name
}
func (p Person) Age() int {
return p.age
}
func main() {
// Empty initialisation
person := Person{}
person.SetName("Harry")
person.SetAge(21)
// Direct access from struct
fmt.Println(person.name)
// Accessing from the getter
fmt.Println(person.Name())
// Initialise upon declaration
person = Person{name:"John", age:25}
// Initialise upon declaration using
// the order of the struct
person = Person{"John", 25}
// Or in reverse / any order if we specify
person = Person{age:25, name:"John"}
fmt.Println(person.Name())
fmt.Println(person.Age())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment