Golang 类型断言教程

本文介绍Go类型推断以及使用示例。类型推断用于获取存储在interface种变量类型及其值。

为什么需要类型推断

我们知道空interface可以接收任意类型值,举例:

// create an empty interface
var a interface {}

//  store value of string type
a = "Hello World"

// store value of integer type
a = 10

这里a为空interface,它既能存储字符串,也能存储整型。这是空接口类型的重要特性,但有时也造成无法确切知道接口中存储变量的具体类型,为了解决该问题,可以使用类型推断。

类型推断

package main
import "fmt"

func main() {

  // create an empty interface
  var a interface {}

  // store integer to an empty interface
  a = 10

  // type assertion
  interfaceValue := a.(int)

  fmt.Println(interfaceValue)

  // 输出 10
}

下面解释这行代码:

interfaceValue := a.(int)

(int) 检查a的值是否为整型,如果是,返回a的值给interfaceValue.否则程序报错并终止。

package main
import "fmt"

func main() {

  // create an empty interface
  var a interface{}

  // store integer to an empty interface
  a = "Golang"

  // type assertion
  interfaceValue := a.(int)

  fmt.Println(interfaceValue)
}

这里空接口值为字符串,a.(int)不为true,因此报错。输出错误信息:

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

避免报错

Go类型推断支持返回多个值,从而避免程序报错,下面代码除了返回值,还有另一个布尔值标识是否类型匹配:

package main
import "fmt"

func main() {

  // create an empty interface
  var a interface{}
  a = 12

  // type assertion
  interfaceValue, booleanValue := a.(int)

  fmt.Println("Interface Value:", interfaceValue)
  fmt.Println("Boolean Value:", booleanValue)

}

输出:

Interface Value: 12
Boolean Value: true

再看一个不匹配场景:

package main
import "fmt"

func main() {

  // create an empty interface
  var a interface{}
  a = "Golang"

  // type assertion
  interfaceValue, booleanValue := a.(int)

  fmt.Println("Interface Value:", interfaceValue)
  fmt.Println("Boolean Value:", booleanValue)

}

输出:

Interface Value: 0
Boolean Value: false

类型不匹配时,仅返回值为false,程序并没报错。

类型选择(Type Switch)

类型选择用于与switch语句中多个case 类型比较接口的具体类型。它与单个类型推断有点差别,case后面是具体类型,而不是值。示例代码如下:

// Go program to illustrate type switch
package main
  
import "fmt"
  
func myfun(a interface{}) {
  
    // Using type switch
    switch a.(type) {
  
    case int:
        fmt.Println("Type: int, Value:", a.(int))
    case string:
        fmt.Println("\nType: string, Value: ", a.(string))
    case float64:
        fmt.Println("\nType: float64, Value: ", a.(float64))
    default:
        fmt.Println("\nType not found")
    }
}
  
// Main method
func main() {
    myfun("GeeksforGeeks")
    myfun(67.9)
    myfun(true)
}

输出结果:

Type: string, Value:  GeeksforGeeks

Type: float64, Value:  67.9

Type not found
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值