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}]
原文链接:https://www.f2er.com/go/188311.html