我有一些不同的结构,例如 Big
和 Small
嵌入在偏移量 0 处。
我如何从代码访问 Small
的结构字段,它对 Big
类型一无所知,但已知 Small
是在偏移量 0 处?
type Small struct {
val int
}
type Big struct {
Small
bigval int
}
var v interface{} = Big{}
// here i only know about 'Small' struct and i know that it is at the begining of variable
v.(Small).val // compile error
似乎编译器在理论上能够操作这样的表达式,因为它知道 Big
类型在偏移量 0 处嵌入了 Small
类型。有什么办法可以做到这一点事情(可能与 unsafe.Pointer
)?
最佳答案
虽然带反射的答案有效,但它会降低性能并且不是 Go 的惯用语言。
我相信你应该使用接口(interface)。像这样
https://play.golang.org/p/OG1MPHjDlQ
package main
import (
"fmt"
)
type MySmall interface {
SmallVal() int
}
type Small struct {
val int
}
func (v Small) SmallVal() int {
return v.val
}
type Big struct {
Small
bigval int
}
func main() {
var v interface{} = Big{Small{val: 3}, 4}
fmt.Printf("Small val: %v", v.(MySmall).SmallVal())
}
输出:
Small val: 3
关于戈朗 : convert struct to embedded at offset 0 struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39143091/