golang 断言是什么


本文摘自php中文网,作者爱喝马黛茶的安东尼,侵删。

Go语言里面有一个语法,可以直接判断是否是该类型的变量: value, ok = element.(T),这里value就是变量的值,ok是一个bool类型,element是interface变量,T是断言的类型。

如果element里面确实存储了T类型的数值,那么ok返回true,否则返回false。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

package main

  

import (

  "fmt"

)

  

type Order struct {

  ordId   int

  customerId int

  callback func()

}

  

func main() {

  var i interface{}

  i = Order{

    ordId:   456,

    customerId: 56,

  }

  value, ok := i.(Order)

  if !ok {

    fmt.Println("It's not ok for type Order")

    return

  }

  fmt.Println("The value is ", value)

}

输出:

1

The value is  {456 56 <nil>}

常见的还有用switch来断言:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

package main

  

import (

  "fmt"

)

  

type Order struct {

  ordId   int

  customerId int

  callback func()

}

  

func main() {

  var i interface{}

  i = Order{

    ordId:   456,

    customerId: 56,

  }

  switch value := i.(type) {

    case int:

      fmt.Printf("It is an int and its value is %d\n", value)

    case string:

      fmt.Printf("It is a string and its value is %s\n", value)

    case Order:

      fmt.Printf("It is a Order and its value is %v\n", value)

    default:

      fmt.Println("It is of a different type")

    }

}

输出:

1

It is a Order and its value is {456 56 <nil>}

golang的语言中提供了断言的功能。golang中的所有程序都实现了interface{}的接口,这意味着,所有的类型如string,int,int64甚至是自定义的struct类型都就此拥有了interface{}的接口,这种做法和java中的Object类型比较类似。那么在一个数据通过func funcName(interface{})的方式传进来的时候,也就意味着这个参数被自动的转为interface{}的类型。

阅读剩余部分

相关阅读 >>

golang实现http代理服务器

剑指 offer-斐波那契数列

golang有web框架吗

【go从学会到学废】(零) golang简介

将 go 作为脚本语言用

golang如何实现协程?

protoc go插件编写之四 (实现生成自己的proto文件)

整理在vscode中go编码发生的问题

锁的使用场景主要涉及到哪些?读写锁为什么会比普通锁快【golang 入门系列十六】

tidb-lite: 用于 golang 数据库相关代码的单元测试

更多相关阅读请进入《golang》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...