duanpen9294 2018-11-23 14:25
浏览 60

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

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条回答 默认 最新

  • doucai4274 2018-11-23 14:38
    关注

    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())
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败