类型断言
单值断言 v.(T) 是什么? 断言失败会怎样?
- 单值断言:
v必须是接口值; - 目标为具体类型: 动态类型必须相同;
- 目标为接口: 动态类型须实现该接口;
- 失败: 直接 panic;
func main() {
var v any = "go"
s := v.(string) // 断言动态类型为 string;失败时 panic
println(s) // go
}
comma ok 断言如何写? 失败时返回什么?
- 安全断言:
value, ok := v.(T)用 bool 表示失败; - 失败时: value 是
T的零值; - 建议: 无法保证类型时优先用此形式;
func main() {
var v any = "go"
s, ok := v.(string) // 失败时返回 string 零值和 false
println(s, ok) // go true
}
type switch 的写法是什么? v.(type) 用在哪里?
- 类型分支:
v.(type)只用于 type switch; - case 内变量: 具有该具体类型;
case nil: 可单独处理 nil 接口;
package main
import "fmt"
func describe(v any) {
switch x := v.(type) { // v.(type) 只能用于 type switch
case int:
fmt.Println("int", x) // x 为 int
case string:
fmt.Println("string", x) // x 为 string
default:
fmt.Println("other")
}
}
func main() {
describe(42)
describe("go")
describe(true)
}
面对不同的类型确定性,应选哪种断言形式?
- 类型已确认、失败属编程错误: 单值断言;
- 类型未知: 用 comma ok;
- 要分别处理多个类型: 用 type switch;
- 细节: 见上文;