跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • 新手求教一个类型断言的问题
未分類
14 6 月 2020

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

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

資深大佬 : inori 5

我理解 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)

  • 資深大佬 : Vegetable

    我去还能这么写…我以前都是判断好了再转一次

  • 資深大佬 : whoami9894

    val.(type)是类型断言的特殊语法,和 val.(int)什么的不一样

  • 資深大佬 : stevenbipt

    .(type)会返回 interface{}的类型,然后使用 switch 匹配类型的 case,这里的 case 甚至可以是接口类型,算是 go 的一个专用语法了

  • 資深大佬 : tidyoux

    简单说,可以认为 i.(type) 返回了 i 的值和类型,switch 比较用的是类型,值是方便程序员用的。

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具