type Employee struct {
id int
name string
address string
position string
salary int
}
func main() {
var dil Employee
dil.id = 1
dil.name = "xuan"
dil.address = "xxx.xxx"
var emp *Employee = &dil
emp.address += "999"
//(*emp).address += "999" 上面语句这样写是一样的
fmt.Printf("id=%d name=%s address=%s", dil.id, dil.name, dil.address)
}
结构体定义的变量与指向该变量的指针,都是同样的可以用点操作符来操作指定的属性,据说这是GO语言的隐式解读引用特性实现的,这点与C语言还是有使用上的差异的。
执行后输出结果如下:
id=1 name=xuan address=xxx.xxx999
type Point struct {
X, Y int
}
type Circle struct {
Point //匿名成员
Radius int
}
type Wheel struct {
Name string
Circle //匿名成员
Spokes int
Desc string
}
func main() {
var w Wheel
w.Spokes = 20
w.Circle.Point.X = 9
w.X = 9
w.Y = 9
w.Radius = 10
fmt.Printf("%#v\n", w)
}
上面例子可以看出,使用匿名成员实际就是只写了一个类型名,并没有变量名,这样系统就会自动生成一个跟类型名同样的变量名, 也就是说, 下面两句的作用是一样的:
w.Circle.Point.X = 9
w.X = 9
格式化输出语句中的 %#v实际是要求将成员变量名也一并打印出来,这样更利于解读,执行的结果如下:
main.Wheel{Name:"", Circle:main.Circle{Point:main.Point{X:9, Y:9}, Radius:10}, Spokes:20, Desc:""}
type Point struct {
X, Y int
}
type Circle struct {
Point //匿名成员
Radius int
}
type Wheel struct {
Name string `json:"WheelName"` //指定json中显示的名
Circle //匿名成员
Spokes int `json:"SpokeNums"` //指定json中显示的名
Desc string `json:"wheel remark,omitempty"` //指定json中显示的名,第二个参数表示为空则不输出
}
func main() {
var wheels = []Wheel{
{"xs1", Circle{Point{8, 8}, 10}, 20, "desc1"},
{"xs2", Circle{Point{6, 6}, 11}, 16, "desc2"},
{"xs3", Circle{Point{9, 9}, 18}, 20, ""},
}
data, err := json.Marshal(wheels) //生成标准json
if err != nil {
log.Fatalf("Json marshaling failed:%s", err)
}
fmt.Printf("%s\n", data)
我们对Wheel结构体成员的加了一些tag标签, 用于其转化为json时,可以更方便用有效的显示有意义的字符串,然后调用了json.Marshal方法将一个数组转化为标准json串,运行结果如下:
[{"WheelName":"xs1","X":8,"Y":8,"Radius":10,"SpokeNums":20,"wheel remark":"desc1"},{"WheelName":"xs2","X":6,"Y":6,"Radius":11,"SpokeNums":16,"wheel remark":"desc2"},{"WheelName":"xs3","X":9,"Y":9,"Radius":18,"SpokeNums":20}]
可以看到成员的名字已经被tag指定的名字替换了,并且omitempty也生效了, 当为空的时候则省略该字段,最后一个数据被省略掉了,如果我们想更便于查看json的内容可以用如下的方式来生成json
data, err = json.MarshalIndent(wheels, "", " ") //生成带有缩进格式的json
if err != nil {
log.Fatalf("Json marshlIndent failed:%s", err)
}
fmt.Printf("%s\n", data)
这样的json更利于理解和阅读,输出结果如下:
[
{
"WheelName": "xs1",
"X": 8,
"Y": 8,
"Radius": 10,
"SpokeNums": 20,
"wheel remark": "desc1"
},
{
"WheelName": "xs2",
"X": 6,
"Y": 6,
"Radius": 11,
"SpokeNums": 16,
"wheel remark": "desc2"
},
{
"WheelName": "xs3",
"X": 9,
"Y": 9,
"Radius": 18,
"SpokeNums": 20
}
]
接下来将json字符串,转换回原始的数组,使用比较简单,因为标准库已经全部封装好了, 使用方式如下:
var testArr []Wheel
if err := json.Unmarshal(data, &testArr); err != nil {
log.Fatalf("Json unmarshaling failed:%s", err)
}
fmt.Println(testArr)
执行结果如下:
[{xs1 {{8 8} 10} 20 desc1} {xs2 {{6 6} 11} 16 desc2} {xs3 {{9 9} 18} 20 }]