Go 使用指向具有反射的结构的指针切片
我试着用围棋练习思考,我读了几篇文章,但似乎我缺少一些基本的理解,也许你们可以弄清楚 我编写了一个简单的应用程序来演示我要实现的目标 通常,我希望函数接收指向结构的指针片段作为接口类型,并使用反射填充数据 再说一遍。这个例子似乎有点没用,但我最小化了我试图实现的目标。我知道如何找到结构的列名,但我在那里没有问题,所以我从示例中删除了它 这就是代码:Go 使用指向具有反射的结构的指针切片,go,reflection,Go,Reflection,我试着用围棋练习思考,我读了几篇文章,但似乎我缺少一些基本的理解,也许你们可以弄清楚 我编写了一个简单的应用程序来演示我要实现的目标 通常,我希望函数接收指向结构的指针片段作为接口类型,并使用反射填充数据 再说一遍。这个例子似乎有点没用,但我最小化了我试图实现的目标。我知道如何找到结构的列名,但我在那里没有问题,所以我从示例中删除了它 这就是代码: package main import ( "log" "reflect" &qu
package main
import (
"log"
"reflect"
"unsafe"
)
type MyTesting struct {
MyBool bool
MyFloat float64
MyString string
}
func addRow(dst interface{}) {
iValue := reflect.ValueOf(dst)
iType := reflect.TypeOf(dst)
// getting the Struct Type (MyTesting)
structType := iType.Elem().Elem().Elem()
// creating an instance of MyTesting
newStruct := reflect.New(structType)
// getting the current empty slice
slice := iValue.Elem()
// appending the new struct into it
newSlice := reflect.Append(slice,newStruct)
// trying to set the address of the varible to the new struct ? the original var is not a pointer so something here
// is clearly wrong. I get the PANIC here, but if i remove that line, then rows stays nil
reflect.ValueOf(&dst).SetPointer(unsafe.Pointer(newSlice.Pointer()))
currentPlaceForRow := newStruct.Elem()
structField := currentPlaceForRow.FieldByName("MyString")
structField.SetString("testing")
}
func main() {
var rows []*MyTesting
addRow(&rows)
log.Print(rows)
}
因此,在一般情况下,函数会获取指向MyTesting
struct的未初始化指针片段。我想在函数中创建第一个slice元素,并将第一个元素中的MyString
的值设置为“testing”
当我尝试执行它时,我得到:
panic: reflect: reflect.Value.SetPointer using unaddressable value
因此,处理反射对我来说有点困惑。。谁能帮我解释一下我在这里遗漏了什么吗?:) 您可以使用
reflect.ValueOf(dst.Elem().Set(newSlice)
reflect.ValueOf(dst.Elem().Set(newSlice)
@mkopriva-yay!:)就这样。。你能把它作为一个答案贴出来让我标记一下吗?根据经验,如果你认为你需要不安全的来进行反思,你可能已经偏离了正轨。