登录
首页 >  Golang >  Go问答

在Go中如何使用反射(reflection)设置结构体中的接口值

来源:stackoverflow

时间:2024-03-28 22:48:28 292浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《在Go中如何使用反射(reflection)设置结构体中的接口值》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

尝试使用“reflect”包设置接口值时遇到了困难。接口值实际上位于结构体的结构体内部。请参阅我的 go 演示代码

基本上,在initproc内部,我想将dummyafunc函数分配给dummya结构中的box字段

package main 

import (
    "fmt"
    "reflect"
)

type Box struct {
    Name               string
    DummyA             interface{}
}

type SmartBox struct {
    Box
}

func dummyAFunc(i int) {
    fmt.Println("dummyAFunc() is here!")
}

func initProc(inout interface{}) {
    // Using "inout interface{}", I can take any struct that contains Box struct
    // And my goal is assign dummyAFunc to dummyA in Box struct

    iType:=reflect.TypeOf(inout)
    iValue:=reflect.ValueOf(inout)
    
    fmt.Println("Type & value:", iType.Elem(), iValue.Elem()) // Type & value: *main.SmartBox &{{ }}

    e := reflect.ValueOf(inout).Elem()
    
    fmt.Println("Can set?", e.CanSet()).      // true
    fmt.Println("NumField", e.NumField())     // panic: reflect: call of reflect.Value.NumField on ptr Value ?????
    fmt.Println("NumMethod", e.NumMethod())   // NumMethod = 0
        
}

func main() {
    smartbox := new (SmartBox)
    initProc(&smartbox)
}

我是 go 新手,我已经阅读了反射定律,但仍然无法弄清楚。请帮忙。谢谢!


正确答案


您正在将 **smartbix 传递给 initproc。因此,当您使用 reflect 的 elem() 取消引用一次时,您仍然会获得一个指针(*smart box)。

由于 new 已经返回一个指针,因此只需使用:

smartbox := new (smartbox)

// initproc(smartbox) // **smartbox
initproc(smartbox) // *smartbox

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

编辑

要更新输入结构体的 dummya 字段,您可以执行以下操作:

func initProc2(v interface{}) error {

    if reflect.TypeOf(v).Kind() != reflect.Ptr {
        return fmt.Errorf("value must be a pointer")
    }

    dv := reflect.ValueOf(v).Elem()

    if dv.Kind() != reflect.Struct {
        return fmt.Errorf("value must be a pointer to a struct/interface")
    }

    const fname = "DummyA" // lookup field name

    f := dv.FieldByName(fname)

    if !f.CanSet() {
        return fmt.Errorf("value has no field %q or cannot be set", fname)
    }

    nv := reflect.ValueOf(dummyAFunc)

    f.Set(nv)

    return nil
}

工作示例:https://play.golang.org/p/VE751GtSGEw

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在Go中如何使用反射(reflection)设置结构体中的接口值》文章吧,也可关注golang学习网公众号了解相关技术文章。

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