📜  Golang 中的类型断言

📅  最后修改于: 2021-10-25 02:11:43             🧑  作者: Mango

Golang 中的类型断言提供对接口变量的确切类型的访问。如果数据类型已经存在于接口中,那么它将检索接口保存的实际数据类型值。类型断言采用接口值并从中提取指定显式类型的值。基本上,它用于消除接口变量的歧义。

句法:

t := value.(typeName)

其中value是类型必须是接口的变量, typeName是我们要检查的具体类型,底层 typeName 值分配给变量t

示例 1:

// Golang program to illustrate 
// the concept of type assertions
package main
  
import (
    "fmt"
)
  
// main function
func main() {
      
    // an interface that has 
    // a string value
    var value interface{} = "GeeksforGeeks"
      
    // retrieving a value
    // of type string and assigning
    // it to value1 variable
    var value1 string = value.(string)
      
    // printing the concrete value
    fmt.Println(value1)
      
    // this will panic as interface
    // does not have int type
    var value2 int = value.(int)
      
    fmt.Println(value2)
}

输出:

GeeksforGeeks
panic: interface conversion: interface {} is string, not int

上面代码中,由于值接口不持有int类型,语句触发panic,类型断言失败。要检查接口值是否包含特定类型,类型断言可以返回两个值,具有 typeName 值的变量和报告断言是否成功的布尔值。这在以下示例中显示:

示例 2:

// Golang program to show type
// assertions with error checking
package main
  
import (
    "fmt"
)
  
// main function
func main() {
      
    // an interface that has 
    // an int value
    var value interface{} = 20024
      
    // retrieving a value
    // of type int and assigning
    // it to value1 variable
    var value1 int = value.(int)
      
    // printing the concrete value
    fmt.Println(value1)
      
    // this will test if interface
    // has string type and
    // return true if found or
    // false otherwise
    value2, test := value.(string)
    if test {
      
        fmt.Println("String Value found!")
        fmt.Println(value2)
    } else {
      
        fmt.Println("String value not found!")
    }
}

输出:

20024
String value not found!