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/[email protected]/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)
	}
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章