结构体:
type student struct {
name string
age int
}
type teacher struct {
name string
}
func main(){
s1 := student{"aaa", 1} // 必须全部赋值
s2 := student{name: "bbb", age: 1}
var s3 student // 地址为第一个成员的地址
s3.name = "ccc"
// s3.age = 1 // 可以只赋值一个,其他是各个类型的零值
fmt.Println(s1.name)
fmt.Println(s2)
fmt.Println(s3)
fmt.Println(s1 == s2) // false,各个属性必须相同
// s4 := teacher{"aaad"}
// fmt.Println(s1 == s4) // invalid operation: s1 == s4 (mismatched types student and teacher)
var s5 student
s5 = s1 // 同类型可以赋值
fmt.Println(s5)
var s_list [3]student
// append(s_list, s1) // first argument to append must be slice; have [3]student
s_list[0] = s1
fmt.Println(s_list)
var a_l = [...]student{s1, s2}
fmt.Println(a_l)
// var a [...]int // 不行
}
结构体是值传递:map是引用传递,作为map的值,改变是因为map是引用传递
type student struct {
name string
age int
}
type teacher struct {
name string
}
func good(m map[int]student) {
// m[1].name = "eeeee" /*cannot assign to struct field m[1].name in map",*/
stu1 := m[1]
stu1.name = "eeeee"
m[1] = stu1
fmt.Println(m)
}
func good2(s student) {
s.name = "eeeee"
fmt.Println(s)
}
func main() {
// var map1 map[int]student // 这种初始化方式会报错误
// map1[1] = student{"kkk", 1} // panic: assignment to entry in nil map
map1 := make(map[int]student)
map1[1] = student{name: "aaa", age: 1}
good(map1)
fmt.Println(map1)
/*结果:作为map的值是引用传递,map是引用传递
map[1:{eeeee 1}]
map[1:{eeeee 1}]
*/
s1 := student{"aaa", 1}
good2(s1)
fmt.Println(s1)
/*结果:结构体是值传递
{eeeee 1}
{aaa 1}
*/
}