range over interface {} który przechowuje kawałek

Biorąc pod uwagę scenariusz, w którym masz funkcję akceptującą t interface{}. Jeśli zostanie ustalone, że t jest plasterkiem, jak mam range nad tym plasterkiem? Nie będę znał przychodzącego typu, takiego jak []string, []int lub []MyType, w czasie kompilacji.

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

Author: Nucleon, 2012-12-25

2 answers

Cóż użyłem reflect.ValueOf i jeśli jest to kawałek, możesz wywołać Len() i Index() na wartości, aby uzyskać len z kawałka i elementu w indeksie. Nie sądzę, że będziesz w stanie użyć zasięgu do tego.

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

 85
Author: masebase,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-03 13:50:46

Nie musisz używać reflection, jeśli wiesz, jakich typów się spodziewać. Użycie przełącznika typu w ten sposób:

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

Sprawdź kod na placu zabaw .

 3
Author: Inanc Gumus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-28 03:56:12