[英]Go lang slice of interface
I am trying to iterate over a slice of interfaces to find my specific struct by id and change the attribute. 我试图遍历接口的一部分以通过id查找我的特定结构并更改属性。
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
当我找到例如B
结构时,我将设置B.ID = xy
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 函数findStepByID
返回一个interface{}
。如果要为ID分配新值,则必须将其显式转换为类型
Here assuming you use case as is to update the result and use updated value.There are two ways you may do it 这里假设您使用用例来更新结果并使用更新后的值,您可以通过两种方式进行操作
Instead of a empty interface interface{}
use a interface with function UpdateID(ID)
defined 代替使用空接口, interface{}
使用定义了函数UpdateID(ID)
的接口
Use a type switch and inside switch only do the update 使用类型开关,而内部开关仅执行更新
I would not suggest second one as it has scope problems 我不建议第二个,因为它有范围问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.