Go 类型断言 /类型判断

value, ok := em.(T);

em 代表要判断的变量

T 代表被判断的类型

value 代表返回的值

ok 代表是否为该类型

注意:1: em 必须为interface 类型才可以进行类型断言

func main() {

	// value, ok := em.(T);
	// em 代表要判断的变量
	// T 代表被判断的类型
	// value 代表返回的值
	// ok 代表是否为该类型

	//注意:1: em 必须为interface 类型才可以进行类型断言
	//s := "xiaoming"
	//if v, ok := s.(string); ok {   //报错! nvalid type assertion: s.(string) (non-interface type string on left)
	//	fmt.Println(v)
	//}

	//将 s2 显示地 转换为 interface{}接口类型 就可以进行类型断言了
	s2 := "xiaoming2"
	if v, ok := interface{}(s2).(string); ok{
		fmt.Println(v)
	}
	// 输出:xiaoming2

}

2.   必须要 先进行 类型断言 才可以继续使用 该类型的函数。

还有一种情况:结构体S ,实现了 A B 两个接口

A接口有 a() 方法, B接口 有b() 方法; 如果结构体S 作为参数 被 传到 一个函数中(该函数 的参数是 interface{}类型)

那么!! 进行与A的类型断言后就只能调用a() 而不能调用b() 因为编译器只知道你目前是A类型,却不知道你目前也是B类型。

import "fmt"

func ServeHTTP(s string) {
	fmt.Println(s)
}

type Handler func(string)

//func panduan(in interface{}) {
//	Handler(in)("xiaoming")   //报错:cannot convert in (type interface {}) to type Handler: need type assertion
//							//必须要 先进行 类型断言 才可以继续使用 该类型的函数。
//}

func panduan(in interface{}){
	if v, ok := in.(Handler); ok {
		v("xiaoming")
	}
}

func main() {
	panduan(Handler(ServeHTTP))
	//输出:xiaoming
}

//还有一种情况:结构体S ,实现了 A B 两个接口
// A接口有 a() 方法, B接口 有b() 方法; 如果结构体S 作为参数 被 传到 一个函数中(该函数 的参数是 interface{}类型)
// 那么!! 进行与A的类型断言后就只能调用a() 而不能调用b() 因为编译器只知道你目前是A类型,却不知道你目前也是B类型。

//举例如: github.com/kataras/iris/v12@v12.1.8/mvc/mvc.go


func (app *Application) handle(controller interface{}) *ControllerActivator {
	// initialize the controller's activator, nothing too magical so far.
	c := newControllerActivator(app.Router, controller, app.Dependencies, app.Sorter, app.ErrorHandler)

	// check the controller's "BeforeActivation" or/and "AfterActivation" method(s) between the `activate`
	// call, which is simply parses the controller's methods, end-dev can register custom controller's methods
	// by using the BeforeActivation's (a ControllerActivation) `.Handle` method.
	if before, ok := controller.(interface {
		BeforeActivation(BeforeActivation)
	}); ok {
		before.BeforeActivation(c)
	}

	c.activate()

	if after, okAfter := controller.(interface {
		AfterActivation(AfterActivation)
	}); okAfter {
		after.AfterActivation(c)
	}

	app.Controllers = append(app.Controllers, c)
	return c
}
 

3. 类型断言 与 switch 结合使用

import "fmt"

// 类型断言 与 switch 结合使用

type Element interface {}

func main() {
	//var e Element = 100
	var e Element = "小明"

	switch value := e.(type) {
	case int :
		fmt.Println("int:", value)
	case string :
		fmt.Println("string:", value)
	default:
		fmt.Println("unknown", value)
	}
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值