mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-11-13 09:16:10 +08:00
11.3
This commit is contained in:
@@ -3,10 +3,10 @@
|
||||
一个接口类型的变量 `varI` 中可以包含任何类型的值,必须有一种方式来检测它的 **动态** 类型,即运行时在变量中存储的值的实际类型。在执行过程中动态类型可能会有所不同,但是它总是可以分配给接口变量本身的类型。通常我们可以使用 **类型断言** 来测试在某个时刻 `varI` 是否包含类型 `T` 的值:
|
||||
|
||||
```go
|
||||
v := varI.(T) // unchecked type assertion
|
||||
v := varI.(T) // unchecked type assertion
|
||||
```
|
||||
|
||||
**varI必须是一个接口变量**,否则编译器会报错:`invalid type assertion: varI.(T) (non-interface type (type of varI) on left)` 。
|
||||
**varI 必须是一个接口变量**,否则编译器会报错:`invalid type assertion: varI.(T) (non-interface type (type of varI) on left)` 。
|
||||
|
||||
类型断言可能是无效的,虽然编译器会尽力检查转换是否有效,但是它不可能预见所有的可能性。如果转换在程序运行时失败会导致错误发生。更安全的方式是使用以下形式来进行类型断言:
|
||||
|
||||
@@ -18,7 +18,7 @@ if v, ok := varI.(T); ok { // checked type assertion
|
||||
// varI is not of type T
|
||||
```
|
||||
|
||||
如果转换合法,`v` 是 `varI` 转换到类型 `T`的值,`ok` 会是 `true`;否则 `v` 是类型 `T` 的零值,`ok` 是 `false`,也没有运行时错误发生。
|
||||
如果转换合法,`v` 是 `varI` 转换到类型 `T` 的值,`ok` 会是 `true`;否则 `v` 是类型 `T` 的零值,`ok` 是 `false`,也没有运行时错误发生。
|
||||
|
||||
**应该总是使用上面的方式来进行类型断言**。
|
||||
|
||||
@@ -30,8 +30,6 @@ if _, ok := varI.(T); ok {
|
||||
}
|
||||
```
|
||||
|
||||
TODO ??:In this form shadowing the variable varI by giving varI and v the same name is sometimes done.
|
||||
|
||||
示例 11.4 type_interfaces.go
|
||||
|
||||
```go
|
||||
|
||||
Reference in New Issue
Block a user