range over interface{} 存储切片
技术问答
677 人阅读
|
0 人回复
|
2023-09-12
|
鉴于你的接受t interface{}. 如果确定t是切片,我怎么样?range覆盖切片?
7 D% w4 g+ z. G$ U[code]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) code]
9 _3 v. L( V( b/ H. y2 D3 W7 m 解决方案:
! m, }$ m; e# w$ ] 嗯,我用reflect.ValueOf,然后,如果是切片,可以调用Len()和Index()获得价值len切片和元素索引。我不认为你会能够使用范围来做到这一点。
4 d0 X, X* c! h, H2 P8 l[code]package mainimport "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)) code] |
|
|
|
|
|