dongwo7858 2017-02-10 12:27
浏览 6
已采纳

进入接口的lang切片

I am trying to iterate over a slice of interfaces to find my specific struct by id and change the attribute.

type A struct {
    ID    ID
    Steps []Step
}

type Step interface{}

type B struct {
    ID       ID
}

type C struct {
   ID     ID
}

func (s *A) findStepByID(id ID) (Step, error) {
    for index, step := range s.Steps {
        switch stepType := step.(type) {
        case A:
            if stepType.ID == id {
                return step, nil
            }
        case B:
            if stepType.ID == id {
                return step, nil
            }
        default:
            return nil, errors.New("no step found")
        }
    }
    return nil, errors.New("no step found")
}

When I found my struct for example B then I will set B.ID = xy

  • 写回答

1条回答 默认 最新

  • duanba8070 2017-02-10 14:18
    关注

    The function findStepByID returns an interface{} .If you want to assign ID with a new value you have to explicitly cast it to a type

    Here assuming you use case as is to update the result and use updated value.There are two ways you may do it

    1. Instead of a empty interfaceinterface{} use a interface with function UpdateID(ID) defined

    2. Use a type switch and inside switch only do the update

    I would not suggest second one as it has scope problems

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本