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
2017/06/30 18:10:36 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/06/30 18:10:37 debugger.go:505: continuing
[{4 4 4 3} {10 10 1 4} {1 1 20 1} {10 10 1 2} {10 30 1 0} {20 20 20 4}]
[{4 4 4 3} {10 10 1 4} {1 1 20 1} {10 10 1 2} {10 30 1 0} {20 20 20 4}]
[{4 4 4 3} {10 10 1 4} {1 1 20 1} {10 10 1 2} {10 30 1 0} {20 20 20 4}]


我们可以通过控制台输出的结果,例如打印的最外层变量结果带中括号,说明你可以象数组那样去访问中括号内部的任意一个元素,如果带花括号表示你可以敲点号后面写字段名称访问它们



package main

import (
"encoding/json"
"fmt"
)

func FromJSON(jsonSrc string,v interface{}) error {
return json.Unmarshal([]byte(jsonSrc),v)
}

func main() {
type person struct {
Name string
Age int
}
json := `[{"Name": "James","Age": 22},{"Name": "Tim","Age": 21}]` //多个字符串格式的json对象

var p []person //定义一个空切片
err := FromJSON(json,&p)
if err == nil {
fmt.Println(p)
}
}

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

相关文章

类型转换 1、int转string 2、string转int 3、string转float ...
package main import s "strings" import...
类使用:实现一个people中有一个sayhi的方法调用功能,代码如...
html代码: beego代码:
1、读取文件信息: 2、读取文件夹下的所有文件: 3、写入文件...
配置环境:Windows7+推荐IDE:LiteIDEGO下载地址:http:...