Fesco
Fesco

Reputation: 147

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.

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

Answers (1)

Sarath Sadasivan Pillai
Sarath Sadasivan Pillai

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

  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

Upvotes: 1

Related Questions