gpt4 book ai didi

go - panic : reflect: call of reflect. Value.FieldByName 接口(interface)值

转载 作者:行者123 更新时间:2023-12-01 22:03:27 24 4
gpt4 key购买 nike

我有一个类型为 interface{} 的变量,我想使用反射更改字段的值。我该怎么做?由于其他要求,变量必须是 interface{} 类型。如果变量不是 interface{} 类型,则一切正常,否则代码抛出

reflect: call of reflect.Value.FieldByName on interface Value

我的代码

package main

import (
"fmt"
"reflect"
)

func main() {
a := struct {
Name string
}{}

// works
reflect.ValueOf(&a).Elem().FieldByName("Name").SetString("Hello")
fmt.Printf("%#v\n", a)

var b interface{}
b = struct {
Name string
}{}
// panics
reflect.ValueOf(&b).Elem().FieldByName("Name").SetString("Hello")
fmt.Printf("%#v\n", b)
}

最佳答案

应用程序必须调用 Elem() 两次以获取结构值:

reflect.ValueOf(&b).Elem().Elem().FieldByName("Name").SetString("Hello")

第一次调用 Elem() 取消引用指向 interface{} 的指针。第二次调用 Elem() 获取接口(interface)中包含的值。

有了这个改变, panic 是reflect.Value.SetString using unaddressable value

应用程序不能直接在接口(interface)中包含的结构值上设置字段,因为接口(interface)中包含的值不可寻址。

将结构值复制到一个临时变量,在临时变量中设置字段并将临时变量复制回接口(interface)。

var b interface{}
b = struct {
Name string
}{}

// v is the interface{}
v := reflect.ValueOf(&b).Elem()

// Allocate a temporary variable with type of the struct.
// v.Elem() is the vale contained in the interface.
tmp := reflect.New(v.Elem().Type()).Elem()

// Copy the struct value contained in interface to
// the temporary variable.
tmp.Set(v.Elem())

// Set the field.
tmp.FieldByName("Name").SetString("Hello")

// Set the interface to the modified struct value.
v.Set(tmp)

fmt.Printf("%#v\n", b)

Run it on the Go playground .

关于go - panic : reflect: call of reflect. Value.FieldByName 接口(interface)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63421976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com