Go 语言没有传统的类和继承概念,而是通过结构体、接口和组合来实现面向对象编程。本部分将深入讲解 Go 语言独特的面向对象设计理念和实践方法。
Go 语言采用组合优于继承的设计理念。本章讲解:
结构体嵌套是 Go 实现组合的核心机制。本章涵盖:
接口是 Go 实现多态的关键。本章介绍:
类型断言用于检查接口值的底层类型。本章讲解:
结构体嵌套:
type Address struct {
City string
Country string
}
type Person struct {
Name string
Address // 匿名嵌套,字段提升
}
// 使用
p := Person{
Name: "张三",
Address: Address{
City: "北京",
Country: "中国",
},
}
fmt.Println(p.City) // 直接访问嵌套字段
接口多态:
type Animal interface {
Speak() string
}
type Dog struct{}
func (d Dog) Speak() string {
return "汪汪"
}
type Cat struct{}
func (c Cat) Speak() string {
return "喵喵"
}
// 多态
func MakeSound(a Animal) {
fmt.Println(a.Speak())
}
类型断言:
var a Animal = Dog{}
// 类型断言
if dog, ok := a.(Dog); ok {
fmt.Println("这是一只狗")
}
// 类型开关
switch v := a.(type) {
case Dog:
fmt.Println("狗:", v.Speak())
case Cat:
fmt.Println("猫:", v.Speak())
}