Go Mark 2
Basic Struct
collections of fields
1type person struct {
2 first string
3 last string
4}
1humanPersona := person{
2 first: "James",
3 last: "Bond",
4}
5
6lName := humanPerson.last
Nested Struct
Structs can be nested
1type car struct {
2 brand string
3 model string
4 doors int
5 frontWheel wheel
6 readWheel wheel
7}
8type wheel struct {
9 radius int
10 material string
11}
12myCar := car{}
13myCar.frontWheel.radius = 5
Embed Struct
Fake (data-only) inheritence
1type car struct {
2 brand string
3 model string
4}
5
6type truck struct {
7 car
8 bedSize int
9}
10
11// embedded struct fields are accessed at top lvl
12redTruck := truck {
13 bedSize: 10,
14 car: car{
15 brand: "dodge",
16 model: "ram",
17 },
18}
19redTruck.brand
20redTruck.bedSize
Struct Methods
structs can have methods. methods are funcs that have a receiver
1type rect struct {
2 width int
3 height int
4}
5
6func (r rect) area() int {
7 return r.width * r.height
8}
9
10var r = rect {
11 width: 5,
12 height: 10,
13}
14r.area()
Interfaces
A set of method signatures. A type "implements" an interface just by having those methods
1type shape interface {
2 area() float64
3}
4
5type rect struct{
6 width, height float64
7}
8
9func (r rect)area() float64 {
10 return r.width * r.height
11}
12
13func printShape(s shape) {
14 fmt.Printf("Area: %v", s.area())
15}