package main
import "fmt"
type Person struct {
name string
age int
sex string
}
func main() {
//方法一
var p1 Person
p1.name = "张三"
p1.age = 18
p1.sex = "男"
fmt.Println(p1)
//方法二
p2 := Person{
name: "李四",
age: 22,
sex: "女",
}
fmt.Println(p2)
//方法三
p3 := new(Person)
p3.sex = "男"
p3.name = "王五"
(*p3).age = 30
p3.age = 32 //语法糖,简化写法
fmt.Println(p3)
p4 := p3 // p3属于指针 地址传递 浅copy
fmt.Println(&p3)
fmt.Println(&p4)
fmt.Println(p3.age)
p4.age = 100
fmt.Println(p3.age)
p5 := p2 //相当于值传递 深copy
fmt.Println(&p5)
fmt.Println(&p2)
fmt.Println(p2.age)
p5.age = 121
fmt.Println(p2.age)
changeAge(p5) //值传递,深copy 改变不了原来的对象
fmt.Println(p5.age)
changeAge1(&p5) //地址传递 浅copy 会影响原来的对象的值
fmt.Println(p5.age)
}
func changeAge(person Person) {
person.age = 123
}
func changeAge1(person *Person) {
person.age = 123
}
继承
type Person struct {
name string
age int
sex string
book Book
}
type Student struct {
Person //提升子段,学生的对象 可以直接访问Person的字段
class string
number int
}
var s1 = student{}
s1.name = "张三"
s1.age = 111
s2 := Student{Person: Person{name: "1212"}, class: "1212121"} //要指定子段名称的话
s3 := Student{Person{"121", 121, "女", Book{"书", 12.1}}, "12121", 121} //不指定字段按顺序的话,需要初始化全部的
fmt.Println(s2)
fmt.Println(s3)
有疑问加站长微信联系(非本文作者)