美文网首页Golang语言社区Go知识库
go语言的类型assertion和类型switch

go语言的类型assertion和类型switch

作者: CodingCode | 来源:发表于2017-09-21 14:32 被阅读49次

首先

首先类型assertion和类型switch只能作用于interface{},不能是其他类型。

func main() {
    var v string = "hello"  // var v interface{} = “hello"
    s, ok := v.(string)
    fmt.Println("s=",s,",ok=",ok)

    switch v.(type) {
    case string:
         fmt.Println("This is a string");
    case int:
         fmt.Println("This is a int");
    default:
         fmt.Println("This is default");
    }
}

得到如下编译错误:

$ go build    
# main
./main.go:XX: invalid type assertion: v.(string) (non-interface type string on left)
./main.go:XX: cannot type switch on non-interface value v (type string)

类型assertion

语法
element.(T)

例子

package main

import "fmt"

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

    s := i.(string)
    fmt.Println(s)

    f := i.(float64) // panic
    fmt.Println(f)
}

运行结果:

hello
panic: interface conversion: interface {} is string, not float64

goroutine 1 [running]:
main.main()
        /$GOPATH/src/main/main.go:11 +0x192
  1. 从i到string的类型assertion成功,返回s等于"hello"。
  2. 从i到float64的类型assertion失败,因为i不是一个float64类型,导致panic。

当然assertion失败没关系,但是不能panic呀,解决方法是:

package main

import "fmt"

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

    s := i.(string)
    fmt.Println(s)

    f, ok := i.(float64) // panic
    if ok {
        fmt.Println(f)
    } else {
        fmt.Println("not a float64")
    }
}

再次运行结果:

$ go build && ./main 
hello
not a float64

当assertion失败的时候,ok返回false,这样就不会发是panic行为。

类型switch

注意的是v必须定义成interface{},否则编译失败。

    var v interface{} = "hello"

    switch v.(type) {
    case string:
         fmt.Println("This is a string");
    case int:
         fmt.Println("This is a int");
    default:
         fmt.Println("This is default");
    }

类型assertion和类型switch非常类似于C++里面多态类型之间的转换和判断。

相关文章

  • go语言的类型assertion和类型switch

    首先 首先类型assertion和类型switch只能作用于interface{},不能是其他类型。 得到如下编译...

  • Go学习笔记(四)

    Go语言的switch语句又分为表达式switch语句和类型switch语句。每一个case可以携带一个表达式或一...

  • 《GO语言圣经》读书笔记 第三章 基础数据类型

    Go语言将数据类型分为四类:** 基础类型、复合类型、引用类型和接口类型 ** 整型 Go语言的数值类型包括几种不...

  • go语言的类型断言(Type Assertion)

    x.(T) 检查x的动态类型是否是T,其中x必须是接口值。 如果T是具体类型类型断言检查x的动态类型是否等于具体类...

  • 王垠批评 golang

    对 Go 语言的综合评价 语法: 类型定义需要很多 “眼球 parse” 语法: switch 语法为了显得简单,...

  • 02-Go语言常量和变量

    Go语言的数据类型 C语言的数据类型 Go语言的数据类型 Go语言各数据类型占用内存空间 Go语言中也可以使用si...

  • go语言指针类型的使用

    go语言的指针类型 简单地说go语言的指针类型和C/C++的指针类型用法是一样的,除了出去安全性的考虑,go语言增...

  • 04-Go语言常量和变量

    Go数据类型 C语言的数据类型image GO语言数据类型image GO数据类型占用的内存空间image 注意点...

  • Go语言标准库之JSON编解码

    Go语言标准库之JSON编解码 基本的类型 Go语言中的数据类型和JSON的数据类型的关系 bool -> JSO...

  • Go语言标准库之JSON编解码

    Go语言标准库之JSON编解码 基本的类型 Go语言中的数据类型和JSON的数据类型的关系 bool -> JSO...

网友评论

    本文标题:go语言的类型assertion和类型switch

    本文链接:https://www.haomeiwen.com/subject/luizsxtx.html