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)
}
}