知识卡片
类型断言须处理不匹配
对接口值做x.(T)是在运行时取出或判断其动态类型。若不能保证匹配,应使用带ok的形式,避免单值断言失败引发panic;空接口的灵活性因此会带来额外运行时检查。类型断言不改变对象本身,也不是任意数值之间的类型转换。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Go Language Foundations · 查看原书依据
A type assertion can be applied to an interface value to “assert” its identity as a concrete type. The syntax takes the general form of x.(T), where x is an expression of an interface and T is the asserted type. Referring to the Shape interface and Circle struct we used above: var s Shape s
参考来源
- 位置:《Cloud Native Go》第03章《Go Language Foundations》(来源项目book-sources;源文件:extracted/Cloud Native Go (Matthew A. Titmus)/_epub-src/OEBPS/ch03.xhtml)
- 结论依据:对接口值做x.(T)是在运行时取出或判断其动态类型。原文相应定义、示例或限制为此结论提供依据;补充纠错与版本边界在正文就近标明。
- 原始内容:A type assertion can be applied to an interface value to “assert” its identity as a concrete type. The syntax takes the general form of x.(T), where x is an expression of an interface and T is the asserted type. Referring to the Shape interface and Circle struct we used above: var s Shape s