-
结构体定义
type Person struct { id int }
-
初始化
// 第一种 var s Student = Student{name:"知了"}
// 第二种 var s1 Student s1.name = "知了" fmt.Println(s1)
// 第三种 s2 := Student{name:"知了"}
-
定义匿名字段(继承)
type Person struct { id int }
type Student struct { Person name string }
s1.id = 3
-
结构体方法定义
func (s Student) eat() { fmt.Println("吃") }
-
方法继承
type Person struct { id int }
func (p Person)hello() { fmt.Println("hello") }
type Student struct { Person name string }
func (s Student) eat() { fmt.Println("吃") }
var s3 Student
s3.eat() s3.hello()
-
方法重写
type Person struct { id int }
func (p Person)hello() { fmt.Println("hello") }
type Student struct { Person name string }
func (s Student) eat() { fmt.Println("吃") }
func (s Student) hello() { fmt.Println("hi")
}
var s3 Student
s3.eat() s3.hello()
项目实战课程 传送门