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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀