2017-02-10 78 views
0

我想迭代一个接口片来找到我的特定结构的id并更改属性。Go lang界面

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

当我发现我的例如B结构,然后我将设置B.ID = xy

+2

这里有什么问题? –

+1

问题是什么? – I159

+0

如何做到这一点,我得到的错误,步骤是一个没有方法的接口 – Fesco

回答

1

。如果你想与你必须明确地将它转换为一种新的价值分配ID findStepByID返回interface{}功能

这里假设你使用的情况下,是更新的结果,并使用更新value.There两种方式你可能做到这一点

  1. 而不是一个空接口interface{}的使用接口定义

  2. 使用类型切换功能UpdateID(ID)和内部交换机仅做更新

我不会建议第二个,因为它有范围的问题