Structs
Examples in
Go
package main
import "fmt"
type rect struct {
width, height int
}
func (r *rect) area() int {
return r.width * r.height
}
func (r rect) perim() int {
return 2*r.width + 2*r.height
}
func main() {
r := rect{width: 10, height: 5}
fmt.Println("area: ", r.area())
fmt.Println("perim:", r.perim())
rp := &r
fmt.Println("area: ", rp.area())
fmt.Println("perim:", rp.perim())
}
Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.
package main
import "fmt"
// Define a struct.
type person struct {
name string
age int
}
// This function initializes a struct variable and returns a pointer to it.
func NewPerson(name string) *person {
p := person{name: name}
p.age = 42
return &p
}
func main() {
// Without keys, you can initialize the members in order that they were defined.
fmt.Println(person{"Bob", 20})
// With keys.
fmt.Println(person{name: "Alice", age: 30})
// Omitted members will be initialized with their "zero value".
fmt.Println(person{name: "Fred"})
// Returning a pointer to an initialized struct.
fmt.Println(&person{name: "Ann", age: 40})
// Calling a function to create our struct.
fmt.Println(NewPerson("Jon"))
// Using the dot operator to access the member values. Works with values and pointers.
s := person{name: "Sean", age: 50}
fmt.Println(s.name)
sp := &s
fmt.Println(sp.age)
sp.age = 51
fmt.Println(sp.age)
}