-2

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.

Dylan
  • 197
  • 1
  • 2
  • 10
  • 2
    Are you sure you should be storing that information as struct fields? Perhaps a map would be more suitable. –  Nov 23 '18 at 14:26
  • @TimCooper Actually i'm using something like a map[email]test so test contains informations related to that email and i have more than 3 fields actually Making one map per fields is a bit too much and not practical I think – Dylan Nov 23 '18 at 14:28
  • 2
    If you don't want to use reflection you could make the function variadic taking pointers to the fields. e.g `something(&t.A, &t.B, &t.C)` – mkopriva Nov 23 '18 at 15:49

1 Answers1

0

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())
}
Alex Pliutau
  • 21,392
  • 27
  • 113
  • 143
  • Yeah that was what I tried to do, but then I realised that in a for loop, we had to call reflect for each iteration. I wanted to set the field I wanna use, just once, at the beginning of the function. – Dylan Nov 23 '18 at 14:48