首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >聊聊golang的类型断言

聊聊golang的类型断言

原创
作者头像
code4it
修改2020-11-30 14:29:34
修改2020-11-30 14:29:34
4720
举报
文章被收录于专栏:码匠的流水账码匠的流水账

本文主要研究一下golang的类型断言

类型断言

代码语言:javascript
复制
x.(T)
  • 断言x不为nil且x为T类型
  • 如果T不是接口类型,则该断言x为T类型
  • 如果T类接口类型,则该断言x实现了T接口

实例1

代码语言:javascript
复制
func main() {
    var x interface{} = 7
    i := x.(int)
    fmt.Println(reflect.TypeOf(i))
    j := x.(int32)
    fmt.Println(j)
}

直接赋值的方式,如果断言为true则返回该类型的值,如果断言为false则产生runtime panic;j这里赋值直接panic

输出

代码语言:javascript
复制
int
panic: interface conversion: interface {} is int, not int32

goroutine 1 [running]:
main.main()
        type_assertion.go:12 +0xda
exit status 2

不过一般为了避免panic,通过使用ok的方式

代码语言:javascript
复制
func main() {
    var x interface{} = 7
    j, ok := x.(int32)
    if ok {
        fmt.Println(reflect.TypeOf(j))
    } else {
        fmt.Println("x not type of int32")
    }
}

switch type

另外一种就是variable.(type)配合switch进行类型判断

代码语言:javascript
复制
func main() {
    switch v := x.(type) {
    case int:
        fmt.Println("x is type of int", v)
    default:
        fmt.Printf("Unknown type %T!\n", v)
    }
}

判断struct是否实现某个接口

代码语言:javascript
复制
type shape interface {
    getNumSides() int
    getArea() int
}
type rectangle struct {
    x int
    y int
}

func (r *rectangle) getNumSides() int {
    return 4
}
func (r rectangle) getArea() int {
    return r.x * r.y
}

func main() {
    // compile time Verify that *rectangle implement shape
    var _ shape = &rectangle{}
    // compile time Verify that *rectangle implement shape
    var _ shape = (*rectangle)(nil)

    // compile time Verify that rectangle implement shape
    var _ shape = rectangle{}
}

输出

代码语言:javascript
复制
cannot use rectangle literal (type rectangle) as type shape in assignment:
        rectangle does not implement shape (getNumSides method has pointer receiver)

小结

  • x.(T)可以在运行时判断x是否为T类型,如果直接使用赋值,当不是T类型时则会产生runtime panic
  • 使用var _ someInterface = someStruct{}可以在编译时期校验某个struct或者其指针类型是否实现了某个接口

doc

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 类型断言
  • 实例1
  • switch type
  • 判断struct是否实现某个接口
  • 小结
  • doc
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档