Reputation: 147
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
Upvotes: 0
Views: 167
Reputation: 7091
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
Instead of a empty interfaceinterface{}
use a interface with function UpdateID(ID)
defined
Use a type switch and inside switch only do the update
I would not suggest second one as it has scope problems
Upvotes: 1