我正在尝试从接口中一般获取任何结构的大小。这适用于按值传递的对象,但我不知道如何在使用接口传递引用时获取对象的大小。
这是一个说明我遇到的问题的示例: https://play.golang.org/p/QXXZm-j7_hZ
package main
import (
"fmt"
"reflect"
"unsafe"
)
type T struct {
c [50]byte
}
func main() {
fmt.Println("Hello, playground")
var t T
s := unsafe.Sizeof(t)
fmt.Println("expected size", s)
getSize(t, &t)
}
func getSize(valueObject interface{}, referenceObject interface{}) {
vs := []uintptr{
unsafe.Sizeof(valueObject),
unsafe.Sizeof(reflect.ValueOf(valueObject)),
reflect.TypeOf(valueObject).Size(), // THIS WORKS FOR VALUE
reflect.TypeOf(reflect.ValueOf(valueObject)).Size(),
0, //reflect.TypeOf(reflect.ValueOf(valueObject).Elem()).Size(), //EXCEPTION ACCESSING ELEM WITH VALUE
0, //reflect.TypeOf(reflect.ValueOf(valueObject).Elem()).Size(), //EXCEPTION ACCESSING ELEM WITH VALUE
0, //unsafe.Sizeof(reflect.ValueOf(valueObject).Elem()), //EXCEPTION ACCESSING ELEM WITH VALUE
0, //unsafe.Sizeof(reflect.TypeOf(reflect.ValueOf(valueObject).Elem())), //EXCEPTION ACCESSING ELEM WITH VALUE
}
fmt.Println("valueObject size", vs)
rs := []uintptr{
unsafe.Sizeof(referenceObject),
unsafe.Sizeof(reflect.ValueOf(referenceObject)),
reflect.TypeOf(referenceObject).Size(),
reflect.TypeOf(reflect.ValueOf(referenceObject)).Size(),
reflect.TypeOf(reflect.ValueOf(referenceObject).Elem()).Size(),
reflect.TypeOf(reflect.ValueOf(referenceObject).Elem()).Size(),
unsafe.Sizeof(reflect.ValueOf(referenceObject).Elem()),
unsafe.Sizeof(reflect.TypeOf(reflect.ValueOf(referenceObject).Elem())),
}
fmt.Println("referenceObject size", rs)
}
这是输出:
expected size 50
valueObject size [8 12 50 12 0 0 0 0]
referenceObject size [8 12 4 12 12 12 12 8]
正如您所看到的,当我使用 传递值时,我可以获得对象的大小reflect.TypeOf(valueObject).Size(),但是当我传递引用时,没有任何东西给我正确的大小。
翻阅古今
相关分类