Go switch type 的类型判断的代码示范

发布时间:2023-03-17浏览次数:0

支持注册ChatGPT Plus的OneKey虚拟卡
绑定Apple Pay、Google Pay、支付宝和微信支付进行日常消费

注册和了解更多 ->

silver

以下代码示范了一个简单的 Go switch type 类型判断:

package main

import "fmt"

func main() {
    var x interface{}
    x = "hello"

    switch x.(type) {
    case int:
        fmt.Println("x is an int")
    case string:
        fmt.Println("x is a string")
    case bool:
        fmt.Println("x is a boolean")
    default:
        fmt.Println("x is of an unknown type")
    }
}

在这个示例中,我们使用了一个空接口变量 x,并将其赋值为一个字符串 "hello"。我们使用了 Go 中的 switch 语句,并使用了 x.(type) 语法来判断 x 的类型。对于不同的类型,我们打印了不同的信息。在这里,我们只列出了 int、string 和 bool 三种类型,但你可以根据需要加入更多的类型。如果无法确定变量的类型,我们将打印出 "x is of an unknown type"。

字节笔记本扫描二维码查看更多内容