94 lines
1.5 KiB
Markdown
94 lines
1.5 KiB
Markdown
|
|
# 03-embedding - 组合与类型断言
|
||
|
|
|
||
|
|
## 知识点讲解
|
||
|
|
|
||
|
|
### 结构体嵌入(组合)
|
||
|
|
|
||
|
|
```go
|
||
|
|
type Address struct {
|
||
|
|
City string
|
||
|
|
Street string
|
||
|
|
}
|
||
|
|
|
||
|
|
type Person struct {
|
||
|
|
Name string
|
||
|
|
Address Address // 嵌套结构体
|
||
|
|
}
|
||
|
|
|
||
|
|
type Employee struct {
|
||
|
|
Person // 匿名嵌入
|
||
|
|
EmployeeID int
|
||
|
|
}
|
||
|
|
|
||
|
|
emp := Employee{
|
||
|
|
Person: Person{Name: "张三"},
|
||
|
|
}
|
||
|
|
fmt.Println(emp.Name) // 可以直接访问嵌入的字段
|
||
|
|
```
|
||
|
|
|
||
|
|
### 接口嵌入
|
||
|
|
|
||
|
|
```go
|
||
|
|
type Reader interface {
|
||
|
|
Read() string
|
||
|
|
}
|
||
|
|
|
||
|
|
type Writer interface {
|
||
|
|
Write(s string)
|
||
|
|
}
|
||
|
|
|
||
|
|
type ReadWriter interface {
|
||
|
|
Reader
|
||
|
|
Writer // 接口组合
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
### 类型断言
|
||
|
|
|
||
|
|
```go
|
||
|
|
var i interface{} = "hello"
|
||
|
|
|
||
|
|
// 方式1:标准断言
|
||
|
|
s := i.(string)
|
||
|
|
|
||
|
|
// 方式2:带检查
|
||
|
|
s, ok := i.(string)
|
||
|
|
if !ok {
|
||
|
|
fmt.Println("类型断言失败")
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
### 类型选择
|
||
|
|
|
||
|
|
```go
|
||
|
|
func printValue(v interface{}) {
|
||
|
|
switch v.(type) {
|
||
|
|
case int:
|
||
|
|
fmt.Println("整数:", v)
|
||
|
|
case string:
|
||
|
|
fmt.Println("字符串:", v)
|
||
|
|
default:
|
||
|
|
fmt.Println("未知类型")
|
||
|
|
}
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
### 重要提示
|
||
|
|
|
||
|
|
- Go使用组合而非继承
|
||
|
|
- 结构体嵌入可以实现类似继承的效果
|
||
|
|
- 类型断言若失败会panic,需谨慎使用
|
||
|
|
- 类型选择用于处理多种类型
|
||
|
|
|
||
|
|
## 学习目标
|
||
|
|
|
||
|
|
完成本练习后,你将:
|
||
|
|
- ✅ 掌握结构体嵌入的使用
|
||
|
|
- ✅ 理解接口嵌入的概念
|
||
|
|
- ✅ 学会使用类型断言
|
||
|
|
- ✅ 掌握类型选择的使用
|
||
|
|
|
||
|
|
## 练习说明
|
||
|
|
|
||
|
|
打开 `main.go`,根据注释提示填充代码,完成后运行 `go test -v` 验证答案。
|