This sample Go program illustrates some basic Go syntax, pay attention to the comments on list/map operations. it outputs as below:
[ `go run box.go` | done: 615.4157ms ]
There are total 5 boxes, biggest one's color BLACK
The last one volume 125000 it's color is BLACK
painting box: {10 10 10 0}
painting box: {20 20 20 4}
painting box: {30 30 30 2}
painting box: {40 40 40 3}
painting box: {50 50 50 1}
The biggest one's color RED
box-- white in color: WHITE
box-- yellow in color: YELLOW
box-- red in color: RED
package main
import (
"fmt"
)
const (
WHITE = iota
BLACK
BLUE
RED
YELLOW
)
type Color byte
func (c Color) String() string { /implement Stringer interface implicitly.
strings := []string{"WHITE", "BLACK", "BLUE", "RED", "YELLOW"}
return strings[c]
}
type (
Box struct {
width, height, depth float64
color Color
}
BoxList []Box
)
func (b Box) volume() float64 {
return b.width * b.height * b.depth
}
func (b *Box) setColor(c Color) {
b.color = c //could be (*b).color=c
//C++ style (*b).color = c
}
func (bl BoxList) BiggestColor() Color {
v := float64(0.0)
k := Color(WHITE)
// i := 0
for _, b := range bl {
if b.volume() > v {
v = b.volume()
k = b.color
}
}
return k
}
func (bl BoxList) paintAll(c Color) {
for i, b := range bl {
fmt.Println("painting box: ", b) /range returns b ,not the reference
bl[i].setColor(c) / b.setColor(c) ///so will not change the color
//C++ style, (&bl[i]).setColor(c)
}
}
func main() {
boxes := BoxList{ ///literally defines a slice of box
Box{10, 10, 10, WHITE},
Box{20, 20, 20, YELLOW},
Box{30, 30, 30, BLUE},
Box{40, 40, 40, RED},
Box{50, 50, 50, BLACK},
}
fmt.Println("There are total ", len(boxes), " boxes,", " biggest one's color", boxes.BiggestColor())
fmt.Println("The last one volume ", boxes[len(boxes)-1].volume(), " it's color is ", boxes[len(boxes)-1].color)
boxes.paintAll(RED)
fmt.Println("The biggest one's color", boxes.BiggestColor())
mboxes := map[string]Box{ /literally defines a map of key:box
"white": {10, 1, 1, WHITE},
"yellow": {20, 2, 2, YELLOW},
"red": {30, 3, 3, RED},
}
for s, b := range mboxes { //range returns key,value. note not their reference
fmt.Println("box--", s, " in color: ", b.color)
}
}