Golang Reflect的一些用法(持續更新)
在Golang專案開發中我們常會使用到空介面interface{}與reflect。下面是作者在學習Golang過程中遇到的一些關於Reflect的用法,即使總結並記錄。
將interface{T} 轉為 interface{*T}:
我們在使用interface{}傳遞函參時,可能會碰到需要將傳遞的值型別T轉變為指標型別*T,從而使他能夠被賦值,可取址。思路:根據T.type New()一個新的指標Type,並對其賦值。
func ifaceValue2Pointer(v interface{}) interface{}{ pv:=reflect.New(reflect.TypeOf(v)) pv.Elem().Set(reflect.ValueOf(v)) return pv.interface() //fmt.Println(reflect.ValueOf(pv).Elem().CanAddr()) ----> true }
將interface{T} 中T轉為 []byte 位元組流形式:
使用場景:例如使用socket建立長連線時,需要傳輸struct型別。思路:儲存struct的指標地址,Len與Cap,通過unsafe包進行轉換。
type SliceMock struct{ addr uintptr lenint capint } func struct2byte(t interface{}) []byte {//在此假設t的例項為值型別 var ts = &t Len := unsafe.Sizeof(*ts) p := reflect.New(reflect.TypeOf(t)) p.Elem().Set(reflect.ValueOf(t)) addr := p.Elem().UnsafeAddr()//取址 tb := &SliceMock{ addr: addr, cap:int(Len), len:int(Len), } return *(*[]byte)(unsafe.Pointer(tb)) } //........... func main() { data := struct2byte(TestStruct{3,100}) var ptestStruct *TestStruct = *(**TestStruct)(unsafe.Pointer(&data)) }