Go 如何从结构中指定要使用的字段?

Go 如何从结构中指定要使用的字段?,go,struct,field,reflect,Go,Struct,Field,Reflect,我有一个由多个相同类型的字段组成的结构 type test struct{ A int B int C int } 我想应用一个函数,对这三个字段做同样的事情,但我每次只想做一个 function something (toto test, cond int) { if (cond == 1){ // then we will use A for the rest of the function }else if (co

我有一个由多个相同类型的字段组成的结构

type test struct{
       A int
       B int
       C int
}
我想应用一个函数,对这三个字段做同样的事情,但我每次只想做一个

function something (toto test, cond int) {
    if (cond == 1){
        // then we will use A for the rest of the function
    }else if (cond == 2) {
        // then we use B etc....
    } ... 

    for mail, v := range bdd {
        if _, ok := someMap[v.A]; !ok {       // use v.A or V.B or V.C     
            delete(bdd, mail)
        }
        ...
    }

    ...
}
这个函数很长,我觉得代码重复了3次很麻烦,因为只有一行代码发生了变化。
我试过用reflect软件包的东西。我认为这是一个危险的想法。

在您的情况下,我会使用map而不是struct,但如果确实需要struct,您可以使用reflect包

v := reflect.ValueOf(x)

for i := 0; i < v.NumField(); i++ {
    fmt.Printf("%v", v.Field(i).Interface())
}
v:=reflect.ValueOf(x)
对于i:=0;i
您确定应该将该信息存储为结构字段吗?也许地图更合适。@TimCooper实际上我用的是类似地图[电子邮件]的东西测试,所以测试包含与电子邮件相关的信息,我有3个以上的字段,实际上每个字段制作一个映射有点太多,不实用,我想如果你不想使用反射,你可以让函数可变,指向字段的指针。e、 g
something(&t.A,&t.B,&t.C)
是的,这就是我试图做的,但后来我意识到在for循环中,我们必须为每个迭代调用reflect。我想在函数的开头设置我想要使用的字段,只设置一次。