go中struct类型和interface类型可以方便实现面向对象的三大特性:封装、继承和多态。
封装
package test
import (
"fmt"
"testing"
)
type Student struct {
name string
age int
}
func (s *Student) getStudentName() string {
return s.name
}
func (s *Student) getStudentAge() int {
return s.age
}
func TestEncapsulation(t *testing.T) {
stu := Student{name: "zzzlll", age: 27}
fmt.Printf("student name is %v, age is %d\n", stu.name, stu.age)
}
student name is zzzlll, age is 27
继承
package test
import (
"fmt"
"testing"
)
type Person struct {
Student
}
type Student struct {
name string
age int
}
func (s *Student) getStudentName() string {
return s.name
}
func (s *Student) getStudentAge() int {
return s.age
}
func TestExtend(t *testing.T) {
p := Person{Student{name: "zzzlll", age: 27}}
fmt.Printf("person name is %v, age is %d\n", p.name, p.age)
}
person name is zzzlll, age is 27
多态
package test
import (
"fmt"
"testing"
)
type Student struct {
name string
age int
}
type Teacher struct {
name string
age int
}
type Human interface {
study()
}
func (s *Student) study() {
fmt.Println("student study")
}
func (t *Teacher) study() {
fmt.Println("teacher study")
}
func TestPolymorphism(t *testing.T) {
var h Human
h = &Student{name: "zzzlll", age: 27}
h.study()
h = &Teacher{name: "aaakkk", age: 27}
h.study()
}
student study
teacher study