如何动态创建一个结构少一个属性? [英] How to dynamically create a struct with one less property?
问题描述
这是我知道的:
- 我的函数的参数 - 我将调用参数
myData
- - 类型为接口{}
。 -
myData
是一个结构体。 -
myData
有一个已知属性路径
。 -
myData
具有0到6之间的任何值,或者其他属性,其中任何一个都不是先验已知的。
- 一次我删除了
path
属性,那么leftover就是30种可能的结构类型之一。
- 一次我删除了
所以我想从 myData
中去掉 path
(或者更准确地说, path
),这样就可以成功地将结构强制转换成其中一种可能类型的生成代码的各个位。
我找到了copyi的例子通过反射来创建一个结构体,但它们通常会创建一个具有相同基础类型的空 ,然后填充它。那么,甚至可以按照我所概述的方式删除一个属性...?您可以使用 noreferrer> reflect.StructOf
从字段列表动态创建结构。
反映
)
type A struct {
Foo string
Bar int
Baz bool //被跳过
}
type B struct {
Foo string
Bar int
func main(){
av:= reflect.ValueOf(A {hello,123,true})
字段:= make([] reflect.StructField,0)
values:= make([] reflect.Value,0)
for i:= 0;我< av.NumField();如果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;我< LEN(字段); (b)}
$ b $. = val.Convert(btyp)
b,ok:= bval.Interface()。(B)
fmt.Println(b,ok)
}
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 typeinterface{}
. myData
is a struct.myData
has a known propertypath
.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...?
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)
}
这篇关于如何动态创建一个结构少一个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!