登录
首页 >  Golang >  Go问答

处理结构指针片段的反射技术

来源:stackoverflow

时间:2024-02-23 11:45:24 101浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《处理结构指针片段的反射技术》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

我正在尝试用 go 练习反射,我读了一些文章,但似乎我缺少一些基本的理解,也许你们可以澄清。

我编写了一个简单的应用程序来演示我想要实现的目标。

一般来说,我想要一个函数来接收指向结构体的指针片段作为接口类型,并使用反射来填充数据。

再次。这个例子似乎有点无用,但我最小化了我想要实现的目标。我知道如何查找结构体的列名,但我没有问题,所以我从示例中删除了它。

所以这是代码:

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 结构的未初始化的指针片段。我想在函数中创建第一个切片元素并将第一个元素中的 mystring 的值设置为“testing”。

当我尝试执行它时,我得到:

panic: reflect: reflect.Value.SetPointer using unaddressable value

所以使用反射对我来说有点令人困惑..任何人都可以阐明我在这里缺少的东西吗? :)


解决方案


您可以使用 reflect.ValueOf(dst).Elem().Set(newSlice)

https://play.golang.org/p/ilDZxHc2H-x

终于介绍完啦!小伙伴们,这篇关于《处理结构指针片段的反射技术》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>