Golang 如何将多个对象添加到切片里的不同方式,空切片的不同定
package main
import ( "fmt" ) func main() { //将多个对象添加到切片的方法1: boxes1 := []Box{} //空切片的定义方法,它等价于make([]Box,0) box := Box{4,4,RED} boxes1 = append(boxes1,box) box = Box{10,10,1,YELLOW} boxes1 = append(boxes1,box) box = Box{1,20,BLACK} boxes1 = append(boxes1,BLUE} boxes1 = append(boxes1,30,WHITE} boxes1 = append(boxes1,box) box = Box{20,box) fmt.Println(boxes1) //将多个对象添加到切片的方法2: boxes2 := BoxList{Box{4,RED},Box{10,YELLOW},Box{1,BLACK},BLUE},WHITE},Box{20,YELLOW}} fmt.Println(boxes2) //将多个对象添加到切片的方法3: boxes3 := new(BoxList) //空切片的定义方法 ,new的对象要是个切片类型的对象 *boxes3 = append(*boxes3,Box{4,RED}) *boxes3 = append(*boxes3,YELLOW}) *boxes3 = append(*boxes3,BLACK}) *boxes3 = append(*boxes3,BLUE}) *boxes3 = append(*boxes3,WHITE}) *boxes3 = append(*boxes3,YELLOW}) fmt.Println(*boxes3) } 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 } func (b *Box) SetColor(c Color) { b.color = c } func (c Color) String() string { strings := []string{"WHITE","BLACK","BLUE","RED","YELLOW"} return strings[c] }
Visual Studio Code 调试控制台输出以下信息: 2017/06/30 18:10:36 server.go:73: Using API v1
我们可以通过控制台输出的结果,例如打印的最外层变量结果带中括号,说明你可以象数组那样去访问中括号内部的任意一个元素,如果带花括号表示你可以敲点号后面写字段名称访问它们
package main Visual Studio Code 调试控制台输出以下信息: 2017/07/01 15:54:39 server.go:73: Using API v1 2017/07/01 15:54:39 debugger.go:97: launching process with args: [/root/code/go/src/contoso.org/book/debug] API server listening at: 127.0.0.1:2345 2017/07/01 15:54:39 debugger.go:505: continuing [{James 22} {Tim 21}] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |