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))
    
}
上一篇下一篇

猜你喜欢

热点阅读