donglongqiao9595 2018-04-05 20:24
浏览 22
已采纳

如何动态创建少一个属性的结构?

Is there a way to copy a generic struct (i.e. a struct whose property names are unknown) and skip a single, known property?

Here is what I know:

  • The parameter to my function--I will call the parameter myData-- is of type interface{}.
  • myData is a struct.
  • myData has a known property path.
  • myData has anywhere from 0 to 6 or so other properties, none of which are known a priori.
  • Once I remove that path property, then the “leftover” is one of say 30 possible struct types.

So I want to strip path out of myData (or more accurately make a copy that omits path) so that various bits of generated code that try to coerce the struct to one of its possible types will be able to succeed.

I have found examples of copying a struct by reflection, but they typically create an empty struct of the same underlying type, then fill it in. So is it even possible to delete a property as I have outlined...?

  • 写回答

1条回答 默认 最新

  • doucheng1891 2018-04-07 06:31
    关注

    You can use reflect.StructOf to dynamically create structs from a list of fields.

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type A struct {
        Foo string
        Bar int
        Baz bool // to be skipped
    }
    
    type B struct {
        Foo string
        Bar int
    }
    
    func main() {
        av := reflect.ValueOf(A{"hello", 123, true})
    
        fields := make([]reflect.StructField, 0)
        values := make([]reflect.Value, 0)
        for i := 0; i < av.NumField(); i++ {
            f := av.Type().Field(i)
            if f.Name != "Baz" {
                fields = append(fields, f)
                values = append(values, av.Field(i))
            }
        }
    
        typ := reflect.StructOf(fields)
        val := reflect.New(typ).Elem()
        for i := 0; i < len(fields); i++ {
            val.Field(i).Set(values[i])
        }
    
        btyp := reflect.TypeOf(B{})
        bval := val.Convert(btyp)
    
        b, ok := bval.Interface().(B)
        fmt.Println(b, ok)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 php 将rtmp协议转hls协议,无法播放
  • ¥15 miniconda安装不了
  • ¥20 python代码编写
  • ¥20 使用MPI广播数据遇到阻塞
  • ¥15 TinyMCE如何去掉自动弹出的“链接…”工具?
  • ¥15 微信支付转账凭证,如何解决
  • ¥15 在win10下使用指纹登录时,界面上的文字最后一个字产生换行现象
  • ¥20 使用AT89C51微控制器和MAX7219驱动器来实现0到99秒的秒表计数,有开始和暂停以及复位功能,下面有仿真图,请根据仿真图来设计c语言程序
  • ¥15 51单片机 双路ad同步采样
  • ¥15 使用xdocreport 生成word