Go语言之“容器”

2017-12-29  本文已影响50人  夏夜星语

1.Struct体现的Go的优雅

1.代码如下,可细细体会struct的魅力

package main

import "fmt"

const(
    WHITE = iota
    BLACK
    BLUE
    RED
    YELLOW
)

type Color byte

type Box struct{
    width, height, depth float64
    color Color
}

type BoxList []Box

func (b Box) Volume() float64 {
    return b.width * b.height * b.depth
}


//change hthe parament, so here is a pointer
func (b *Box) SetColor(c Color) {
    b.color = c
}


func (bl BoxList) BiggestColor() Color {
    v := 0.00
    k := Color(WHITE)
    for _, b := range bl {
        if bv := b.Volume(); bv > v {
            v = bv
            k = b.color
        }
    }
    return k
}

func (bl BoxList) PaintItBlack() {
    for i, _ := range bl {
        bl[i].SetColor(BLACK)
    }
}

func (c Color) String() string {
    strings := []string {"WHITE", "BLACK", "BLUE", "RED", "YELLOW"}
    return strings[c]
}

func main(){
    boxes := BoxList{
        Box{4, 4, 4, RED},
        Box{10, 10, 1, YELLOW},
        Box{1, 1, 20, BLACK},
        Box{10, 10, 1, BLUE},
        Box{10, 30, 1, WHITE},
        Box{20, 20, 20, YELLOW},
    }
    fmt.Println("We have %d boxes in our set\n", len(boxes))
    fmt.Println("The Volume of the first box is", boxes[0].Volume())
    fmt.Println("The color of the last one is", boxes[len(boxes)-1].color)
    fmt.Println("The biggest one is", boxes.BiggestColor().String())
    fmt.Println("Let's paint them all black")
    boxes.PaintItBlack()
    fmt.Println("The color of the second one is", boxes[1].color.String())
    fmt.Println("Obviously, now, the biggest one is", boxes.BiggestColor())
    fmt.Println("I want to change the third color to YELLOW")
    fmt.Println("Before changed, the color is", boxes[2].color.String())
    boxes[2].SetColor(BLUE)
    //直接打印color属性
    fmt.Println("After changed, the color is", boxes[2].color)
    //检测RED是否为数字3
    fmt.Println(RED)
}

2.程序运行结果:

struct

3.尤其需要注意的是:setColor()这个函数,调用者(receiver)是Box的指针,注意*(b Box)

上一篇下一篇

猜你喜欢

热点阅读