patterngoCritical
range over interface{} which stores a slice
Viewed 0 times
storessliceoverinterfacerangewhich
Problem
Given the scenario where you have a function which accepts
Go Playground Example: http://play.golang.org/p/DNldAlNShB
t interface{}. If it is determined that the t is a slice, how do I range over that slice?func main() {
data := []string{"one","two","three"}
test(data)
moredata := []int{1,2,3}
test(data)
}
func test(t interface{}) {
switch reflect.TypeOf(t).Kind() {
case reflect.Slice:
// how do I iterate here?
for _,value := range t {
fmt.Println(value)
}
}
}Go Playground Example: http://play.golang.org/p/DNldAlNShB
Solution
Well I used
Go Playground Example: http://play.golang.org/p/gQhCTiwPAq
reflect.ValueOf and then if it is a slice you can call Len() and Index() on the value to get the len of the slice and element at an index. I don't think you will be able to use the range operate to do this.package main
import "fmt"
import "reflect"
func main() {
data := []string{"one","two","three"}
test(data)
moredata := []int{1,2,3}
test(moredata)
}
func test(t interface{}) {
switch reflect.TypeOf(t).Kind() {
case reflect.Slice:
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
fmt.Println(s.Index(i))
}
}
}Go Playground Example: http://play.golang.org/p/gQhCTiwPAq
Code Snippets
package main
import "fmt"
import "reflect"
func main() {
data := []string{"one","two","three"}
test(data)
moredata := []int{1,2,3}
test(moredata)
}
func test(t interface{}) {
switch reflect.TypeOf(t).Kind() {
case reflect.Slice:
s := reflect.ValueOf(t)
for i := 0; i < s.Len(); i++ {
fmt.Println(s.Index(i))
}
}
}Context
Stack Overflow Q#14025833, score: 183
Revisions (0)
No revisions yet.