有關golang反射的內容,網上有大量講述,請自行google——"golang反射三法則"
下面主要反射在實際中的一種應用,插件注冊與插件管理
package main
import (
"fmt"
"reflect"
)
type MyInterface interface {
Test()
}
type Mytype1 struct {
A string
B string
}
func (m Mytype1) Test() {
fmt.Println("test type1", m)
}
type Mytype2 struct {
A string
B string
}
func (m Mytype2) Test() {
fmt.Println("test type2", m)
}
func main() {
// testType1 testType2模擬兩個注冊的插件,實際可在各.go的init()方式實現
testType1 := reflect.TypeOf((*Mytype1)(nil)).Elem()
testType2 := reflect.TypeOf((*Mytype2)(nil)).Elem()
types := []reflect.Type{testType1, testType2}
fmt.Println("types:", types)
// 模擬插件管理,統一調用
var instance interface{}
for _, testType := range types {
instance = reflect.New(testType).Interface()
if myinterface, ok := instance.(MyInterface); ok {
//模擬統一調用
myinterface.Test()
}
}
}
輸出:
types: [main.Mytype1 main.Mytype2]
test type1 { }
test type2 { }