【Go语言学习】断言:形如A.(T)

 

形如A.(T)
其中A只能为interface, T为类型, 可以是interface 或者其他类型. string, int, struct等.

1. 若T为变量类型. 则用于判断转换为对应的变量类型. 这种用法可以使得一个函数接受多类型的变量

func VarType(var interface {})(err error){
  switch t := var.(type){
      case string:
          //add your operations
      case int8:
          //add your operations
      case int16:
          //add your operations
      default:
          return errors.New("no this type")
  }
}

//空接口包含所有的类型,输入的参数均会被转换为空接口
//变量类型会被保存在t中

 

 

2.若T为interface, 则可以用用来判断A这个接口类型是否实现了特定接口

package main

import (
    "fmt"
    "strconv"
)

type I interface{
    Get() int
    Put(int)
}

type P interface{
    Print()
}
//定义结构体,实现接口I
type S struct {
    i int
}
func (p *S) Get() int {
    return p.i
}
func (p *S) Put(v int ) {
    p.i = v
}
func (p *S) Print() {
    fmt.Println("interface p:" + strconv.Itoa(p.i))
}

//使用类型断言
func GetInt( some interface {}) int {
    if sp, ok := some.(P); ok {       // 此处断言some这个接口后面隐藏的变量实现了接口P 从而调用了. P接口中的函数Print.
        sp.Print()
    }

    return some.(I).Get()
}

func main(){
    s := &S{i:5}
    // a := GetInt(s)
    fmt.Println(GetInt(s))
}

这是类型断言的简单用法,这一用法在go语言源代码中出现很频繁。熟练掌握,能够更有效地阅读学习golang的源码。

参考:https://blog.csdn.net/Kiloveyousmile/article/details/78736718

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值