范围覆盖存储切片的接口{} [英] range over interface{} which stores a slice

查看:112
本文介绍了范围覆盖存储切片的接口{}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到您有一个接受 t interface {} 的函数的场景。如果确定 t 是一个切片,那么该切片上的范围如何?我不知道传入的类型,例如 [] string [] int [] MyType ,在编译时。

Given the scenario where you have a function which accepts t interface{}. If it is determined that the t is a slice, how do I range over that slice? I will not know the incoming type, such as []string, []int or []MyType, at compile time.

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)
        }
    }
}

前往游乐场示例: http:// play.golang.org/p/DNldAlNShB

推荐答案

我用 reflect.ValueOf 然后如果它是一个切片,您可以调用 Len() Index()取得切片和元素的索引处的 len 值。我认为你不能使用范围操作来做到这一点。

Well I used 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))
        }
    }
}

前往游乐场示例: http://play.golang.org/p/gQhCTiwPAq

这篇关于范围覆盖存储切片的接口{}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆