我有一个函数遍历作为参数传递的接口的所有字段.为了实现这一点,我正在使用反射.问题是我不知道如何获取非指针字段的地址.这是一个例子:
type Z struct {
Id int
}
type V struct {
Id int
F Z
}
type T struct {
Id int
F V
}
Run Code Online (Sandbox Code Playgroud)
上面的代码代表我的测试结构.现在这里是遍历指定结构的实际函数,并列出了有关它的详细信息:
func InspectStruct(o interface{}) {
val := reflect.ValueOf(o)
if val.Kind() == reflect.Interface && !val.IsNil() {
elm := val.Elem()
if elm.Kind() == reflect.Ptr && !elm.IsNil() && elm.Elem().Kind() == reflect.Ptr {
val = elm
}
}
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
for i := 0; i < val.NumField(); i++ {
valueField := …Run Code Online (Sandbox Code Playgroud) 我几天前刚刚开始学习 Go。今天,我们在调试一段代码一段时间时,发现了一些看起来与 Go 违反直觉的事情。
首先我们定义了一个接口和一个实现它的数据结构。
type Executer interface {
Execute()
}
type whatever struct {
name string
}
func (this *whatever) Execute() {
log.Println(this.name)
}
Run Code Online (Sandbox Code Playgroud)
现在考虑我有一个 nil 指针,whatever并且我尝试调用该方法Execute。在我迄今为止使用过的其他面向对象语言中,这会在调用方法(即w.Execute())时调用空指针错误,因为对象指针为空。有趣的是,在Go中,调用该方法时,Execute当我尝试取消引用时,该方法会发生空指针错误this.name。为什么不在调用该方法时呢?
func main() {
var w *whatever
w.Execute()
}
Run Code Online (Sandbox Code Playgroud)
所以,我现在想了解的是,这怎么可能?这是否意味着 Go 仅在编译时进行早期方法绑定,而在运行时没有方法与特定对象的绑定?