How to specify the field we wanna use from a struct?

74 Views Asked by At

I have a struct composed of multiple fields of same type.

type test struct{
       A int
       B int
       C int
}

I want to apply a function that does the same things to the three fields, but I only wanna do it on one each time.

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)
        }
        ...
    }

    ...
}

The function is really long and I it bothers me to have the code duplicated like 3 times just for one line that changes. I tried things with the reflect package. I think it's a dangerous idea to go into that.

1

There are 1 best solutions below

1
On

In your situation I'd use map instead of struct, but if struct is really required you can use reflect package.

v := reflect.ValueOf(x)

for i := 0; i < v.NumField(); i++ {
    fmt.Printf("%v", v.Field(i).Interface())
}