.() 类型断言

当断言正确,效果相当于直接赋值

  1. func main() {
  2. var i interface{} = "hello"
  3. s, _ := i.(string)
  4. println(s)
  5. fmt.Println(reflect.TypeOf(s))
  6. }
  7. 输出:
  8. hello
  9. string

当断言不正确,效果相当于是在声明变量,声明类型就是右边的类型

  1. func main() {
  2. var i interface{} = "hello"
  3. s, _ := i.(int)
  4. println(s)
  5. fmt.Println(reflect.TypeOf(s))
  6. }
  7. 输出:
  8. 0
  9. int

.(type)

不是类型断言,没有成功不成功. 就相当于直接赋值,按类型选择执行case。

  1. func main() {
  2. var i interface{} = 3
  3. switch x := i.(type) { // .(type)只能用于switch结构中
  4. case int:
  5. println(x)
  6. println(i)
  7. fmt.Println("typeof x:", reflect.TypeOf(x))
  8. fmt.Println("typeof i:", reflect.TypeOf(i))
  9. fmt.Println(x)
  10. fmt.Println(i)
  11. default:
  12. fmt.Println("default")
  13. }
  14. }
  15. 输出:
  16. 3
  17. (0x109d300,0xc420084008)
  18. typeof x: int
  19. typeof i: int // interface{}的当前类型
  20. 3
  21. 3

我们知道interface{}由两部分组成。正如用println(i)打印结果,一个是类型,一个实际值有关系。
拿interface{}的类型去比选择符合的case,然后x相当于被直接赋值。

https://research.swtch.com/interfaces