range over interface{} which stores a slice

后端 未结 3 1028
情深已故
情深已故 2020-12-02 06:54

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 ov

3条回答
  •  鱼传尺愫
    2020-12-02 07:05

    You don't need to use reflection if you know which types to expect. You can use a type switch, like this:

    package main
    
    import "fmt"
    
    func main() {
        loop([]string{"one", "two", "three"})
        loop([]int{1, 2, 3})
    }
    
    func loop(t interface{}) {
        switch t := t.(type) {
        case []string:
            for _, value := range t {
                fmt.Println(value)
            }
        case []int:
            for _, value := range t {
                fmt.Println(value)
            }
        }
    }
    

    Check out the code on the playground.

提交回复
热议问题