learning Go

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)
    }

}









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值