这是一个创建于 1948 天前的主题,其中的信息可能已经有所发展或是发生改变。
我理解 go 断言返回的应该是对应类型的对象,比如说
package main
import (
"fmt"
)
func findType(i interface{}) {
switch x := i.(type) {
case int:
fmt.Println(x, "is int")
case string:
fmt.Println(x, "is string")
case nil:
fmt.Println(x, "is nil")
default:
fmt.Println(x, "not type matched")
}
}
func main() {
findType(10) // int
findType("hello") // string
var k interface{} // nil
findType(k)
findType(10.23) //float64
}
这里 x 应该是具体类型的值 10, "hello"之类的,为什么可以和 int string 这些 case 匹配呢?
4 条回复 2020-06-22 16:58:16 +08:00  | | 1 Vegetable 2020-06-22 13:16:02 +08:00 我去还能这么写...我以前都是判断好了再转一次 |
 | | 2 whoami9894 2020-06-22 13:24:40 +08:00 val.(type)是类型断言的特殊语法,和 val.(int)什么的不一样 |
 | | 3 stevenbipt 2020-06-22 15:08:42 +08:00 1 .(type)会返回 interface{}的类型,然后使用 switch 匹配类型的 case,这里的 case 甚至可以是接口类型,算是 go 的一个专用语法了 |
 | | 4 tidyoux 2020-06-22 16:58:16 +08:00 简单说,可以认为 i.(type) 返回了 i 的值和类型,switch 比较用的是类型,值是方便程序员用的。 |