Iterate over an interface

后端 未结 2 968
面向向阳花
面向向阳花 2020-12-04 00:56

I want to create a function that takes either a map or an array of whatever and iterates over it calling a function on each item which knows what to do with whatever types i

2条回答
  •  既然无缘
    2020-12-04 01:29

    For your example to work, you would need to build an array of interface{} (or a map), in order for the right type to be detected:

    // This won't work, as the .(type) would be []S
    someS := []S{S{}}
    DoTheThingToAllTheThings(someS)
    
    // This will: it will go in case []interface{}:
    someSI := make([]interface{}, len(someS))
    for i, s := range someS {
        someSI[i] = s
    }
    DoTheThingToAllTheThings(someSI)
    

    See a full example here.

    But that means you would still work with interface{} in your DoTheThing function.
    There is no real generic here, as I mentioned in "What would generics in Go be?".

提交回复
热议问题