新手求教一个类型断言的问题

2020-06-22 13:11:49 +08:00
 inori
我理解 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 匹配呢?
1814 次点击
所在节点    Go 编程语言
4 条回复
Vegetable
2020-06-22 13:16:02 +08:00
我去还能这么写...我以前都是判断好了再转一次
whoami9894
2020-06-22 13:24:40 +08:00
val.(type)是类型断言的特殊语法,和 val.(int)什么的不一样
stevenbipt
2020-06-22 15:08:42 +08:00
.(type)会返回 interface{}的类型,然后使用 switch 匹配类型的 case,这里的 case 甚至可以是接口类型,算是 go 的一个专用语法了
tidyoux
2020-06-22 16:58:16 +08:00
简单说,可以认为 i.(type) 返回了 i 的值和类型,switch 比较用的是类型,值是方便程序员用的。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/683717

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX