go struct

Sat, Jan 16, 2016
package main

import (
	"fmt"
)

var testFuncs = []func(){
	//map取值返回的是值而非引用
	func() {
		passwd := map[int]struct {
			name     string
			password int
		}{
			1: {"user1", 10},
			2: {"user2", 20},
		}
		u1 := passwd[1]
		u1.password = 123
		fmt.Printf("user1: %v,%v\n", passwd[1], u1)

	},
	// map通过迭代器返回的元素次序是随机的
	func() {
		users := map[string]string{
			"root":      "admin",
			"superuser": "super power",
			"user":      "normal power",
		}
		for k, v := range users {
			fmt.Printf("k:%v,v:%v\n", k, v)
		}
	},
	// struct拥有补位字段后不能序列初始化,必须指明值的名字
	func() {
		type Node struct {
			_    int
			id   int
			data []byte
			next *Node
		}
		n1 := Node{
			id:   1,
			data: []byte("root"),
			next: nil,
		}
		fmt.Println(n1)
	},
	// 结构体的首元素的指针与结构体相同
	func() {
		type User struct {
			id   int
			name string
		}

		type Manager struct {
			User
			value int
		}
		m := Manager{User{1, "Tom"}, 2}

		fmt.Printf("Manager: %p, %v\n", &m, &m)
		fmt.Printf("User: %p, %v\n", &m.User, &m.User)
		fmt.Printf("id: %p, %v\n", &m.id, &m.id)
	},
}

func main() {
	for i, f := range testFuncs {
		fmt.Println("test", i+1)
		f()
	}
}