You can use the reflect package to iterate over arbitrary fragments. But the implementation of special cases (for example, []int ) is clearly faster and often performed in addition to preventing reflection in ordinary cases.
package main import "fmt" import "reflect" func foo(values interface{}) { rv := reflect.ValueOf(values) if rv.Kind() != reflect.Slice { return } n := rv.Len() for i := 0; i < n; i++ { value := rv.Index(i).Interface() fmt.Println(value) } } func main() { foo([]int{1, 3, 3, 7}) }
Edit: I'm not sure why anyone voted for the question and my answer, but there are times when you need to deal with such code. Even the standard library contains a lot of things, see "fmt", "gob", "json", "xml" and "template", for example. The interrogator may face a similar problem.
source share