回答

收藏

range over interface{} 存储切片

技术问答 技术问答 717 人阅读 | 0 人回复 | 2023-09-12

鉴于你的接受t interface{}. 如果确定t是切片,我怎么样?range覆盖切片?
; S0 a0 X" g1 T( v[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]               
7 L5 n( w5 y+ y6 `    解决方案:                                                                % ]  O) H4 G6 B: }9 i( y1 J/ B
                                                                嗯,我用reflect.ValueOf,然后,如果是切片,可以调用Len()和Index()获得价值len切片和元素索引。我不认为你会能够使用范围来做到这一点。; B; o: V" y9 J) O. `
[code]package mainimport &quot;fmt&quot;import &quot;reflect&quot;func main()      data := []string{&quot;one&quot;,&quot;two&quot;,&quot;three&quot;}    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]
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则