string - 如何在 Go 中使用反射设置一个指向字符串的结构成员

标签 string pointers reflection go struct

我正在尝试使用反射来设置指针。 elasticbeanstalk.CreateEnvironmentInput 有一个 SolutionStackName 字段,它是 *string 类型。当我尝试设置任何值时出现以下错误:

panic: reflect: call of reflect.Value.SetPointer on ptr Value

这是我的代码:

    ...
newEnvCnf := new(elasticbeanstalk.CreateEnvironmentInput)
checkConfig2(newEnvCnf, "SolutionStackName", "teststring")
    ...
func checkConfig2(cnf interface{}, key string, value string) bool {
    log.Infof("key %v, value %s", key, value)

    v := reflect.ValueOf(cnf).Elem()
    fld := v.FieldByName(key)

    if fld.IsValid() {
        if fld.IsNil() && fld.CanSet() {
            fld.SetPointer(unsafe.Pointer(aws.String(value)))
//aws.String returns a pointer

...

这是日志输出

time="2016-02-20T23:54:52-08:00" level=info msg="key [SolutionStackName], value teststring" 
    panic: reflect: call of reflect.Value.SetPointer on ptr Value [recovered]
        panic: reflect: call of reflect.Value.SetPointer on ptr Value

最佳答案

Value.SetPointer()只能在值的种类是 reflect.UnsafePointer 时使用(如 Value.Kind() 所报告),但你的是 reflect.Ptr 所以 SetPointer() 将 panic (如文档所述)。

只需使用 Value.Set()更改结构字段值的方法(是否为指针,无关紧要)。它需要一个 reflect.Value 类型的参数您可以通过调用 reflect.ValueOf() 获得,并简单地传递参数value的地址:

fld.Set(reflect.ValueOf(&value))

测试它:

type Config struct {
    SolutionStackName *string
}

c := new(Config)
fmt.Println(c.SolutionStackName)
checkConfig2(c, "SolutionStackName", "teststring")
fmt.Println(*c.SolutionStackName)

输出(在 Go Playground 上尝试):

<nil>
teststring

关于string - 如何在 Go 中使用反射设置一个指向字符串的结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35533837/

相关文章:

arrays - 将字符串值保存到数组中时出现 Powershell 错误

C - 结构数组元素交换

C++ 在运行时确定多态对象的类型

string - 将两个不同列上第 n 次出现的 'foo' 和 'bar' 替换为相应列中所提供文件的第 n 行的数字

c++ - L做什么的?

c - 如何使用 fread() 将文件内容加载到 C 字符串数组的第二个元素中?

javascript - 将对象的属性和值转换为键值对数组

c# - 什么是 System.Reflection.RuntimePropertyInfo 以及如何比较它?

c++ - 如何使用 Visual Studio 6 C++ 检测字符串中的换行符

c - printf 改变值