Golang Tip:判断两个类型之间是否能转换
2018-05-10 本文已影响0人
幸运排骨虾
主要用到Go语言的反射(reflect)。reflect.Type
接口有一个方法ConvertibleTo
就是判断一个类型是否能转换为另一个类型。
package main
import (
"fmt"
"reflect"
)
type Address [20]byte
func main() {
fmt.Println("Hello, playground")
//v := make([]byte,20)
var v [20]byte
vtype := reflect.ValueOf(v).Type()
fmt.Printf("type slice:%v\n", vtype)
var addr Address
atype := reflect.ValueOf(addr).Type()
fmt.Printf("type address:%v\n", atype)
fmt.Println("convertible:", vtype.ConvertibleTo(atype))
}