繁体   English   中英

使用反射设置指向结构中切片的 nil 指针

[英]setting a nil pointer to a slice in a struct using reflection

我正在使用 go 练习反射,我正在尝试实现以下目标,即拥有一个结构类型,其字段是指向一段字符串的指针。

现在指针为零,我想创建切片,添加一个值并将该指针设置在结构中以指向新创建的切片,并使用反射完成所有这些。

我创建了以下示例代码来演示我在做什么:

package main

import (
    "log"
    "reflect"
)

type UserInfo struct {
    Name   string
    Roles  *[]string
    UserId int
}


func main() {
    var myV UserInfo
    myV.Name="moshe"
    myV.UserId=5
    v := reflect.ValueOf(&myV.Roles)
    t := reflect.TypeOf(myV.Roles)
    myP := reflect.MakeSlice(t.Elem(),1,1)
    myP.Index(0).SetString("USER")
    v.Elem().Set(reflect.ValueOf(&myP)) <-- PANIC HERE
    log.Print(myV.Roles)
}

这使消息恐慌

panic: reflect.Set: value of type *reflect.Value is not assignable to type *[]string

当然,切片不会创建指针,所以如果我这样做:

v.Elem().Set(myP.Convert(v.Elem().Type()))

我得到

panic: reflect.Value.Convert: value of type []string cannot be converted to type *[]string

但是当我尝试转换地址时

v.Elem().Set(reflect.ValueOf(&myP).Convert(v.Elem().Type()))

我得到

panic: reflect.Value.Convert: value of type *reflect.Value cannot be converted to type *[]string

我还缺少什么?

谢谢!

您正在尝试使用来设定值reflect.Value指针到reflect.Value ,这是绝对不一样的*[]string

逐步建立价值并向外工作:

// create the []string, and set the element
slice := reflect.MakeSlice(t.Elem(), 1, 1)
slice.Index(0).SetString("USER")

// create the *[]string pointer, and set its value to point to the slice
ptr := reflect.New(slice.Type())
ptr.Elem().Set(slice)

// set the pointer in the struct
v.Elem().Set(ptr)

https://play.golang.org/p/Tj_XeXNNsML

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM