Last active
December 30, 2015 00:19
-
-
Save hazbo/7748238 to your computer and use it in GitHub Desktop.
Basic structure with setters and getters in Go.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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