原文链接: 1. 用于判断变量类型

demo如下:

  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. 判断某个接口类型是否实现了特定接口

为实现这一目标,代码如下:

if t, ok := something.(I) ; ok {
// 对于某些实现了接口I的
// t是其所拥有的类型
}

如果已经确定了something实现了接口I,可以直接写出下面的代码:

//在确定了something实现了接口I的情况下
//t时something所拥有的类型
//这说明ok
t := something.(I)

当然,也可以封装在一个函数中:

func IsImplement(interface {}) bool{
  _, ok := something.(I);
  return ok
}

注意

something必须为接口(Interface)类型,才可以使用类型断言。假如是其他类型,使用类型断言时,需要转换,最好的方法是定义函数,封装类型断言方法。

分别运行以下代码,看看未实现特定接口的类型使用断言会发生什么:
demo1.go

type I interface{
Get() int
Put(int)
} //定义结构体,实现接口I
type S struct {
i int
}
func (p *S) Get() int {
return p.i
}
func (p *S) Put(v int ) {
p.i = v
} //使用类型断言
func GetInt( some interface {}) int {
return some.(I).Get()
} func main(){
var some = &S{i:}
fmt.Println(GetInt(some))
}

demo2.go

type I interface{
Get() int
Put(int)
} //定义结构体,实现接口I
type S struct {
i int
}
func (p *S) Get() int {
return p.i
}
func (p *S) Put(v int ) {
p.i = v
} //使用类型断言
func GetInt( some interface {}) int {
return some.(I).Get()
} func main(){
var i int =
fmt.Println(GetInt(i))
}