0x00 引言
再简单的事情,也需要有人去做。
0x01 成员变量
type Person struct {
name string
age int
}
person := Person{"mike",18}
fmt.Println(person)
0x02 成员函数
func (person *Person) showInfo() {
fmt.Printf("My name is %s , age is %d ",person.name,person.age)
}
func (person *Person) setAge(age int) {
person.age = age
}
person := Person{"mike",18}
person.showInfo()
person.setAge(20)
fmt,Println(person)
0x03 继承
没有关键字的继承。
type Student struct {
Person
id int
score int
}
func (student *Student) showInfo() {
fmt.Println("I am a student ...")
}
func (student *Student) read() {
fmt.Println("read book ...")
}
student := Student{Person{"jake",16},1001,99}
student.showInfo()
student.setAge(22)
student.read()
0x04 多态
package main
import "fmt"
type Human interface {
speak(language string)
}
type Chinese struct {
}
type American struct {
}
func (ch Chinese) speak(language string ) {
fmt.Printf("speck %s\n",language)
}
func (am American ) speak(language string ) {
fmt.Printf("speck %s\n",language)
}
func main() {
var ch Human
var am Human
ch = Chinese{}
am = American{}
ch.speak("Chinese")
am.speak("English")
}