range over interface{} which stores a slice

后端 未结 3 1023
情深已故
情深已故 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:28

    there is one exception from the way interface{} behaves, @Jeremy Wall gave already pointer. if the passed data is defined as []interface{} initially.

    package main
    
    import (
        "fmt"
    )
    
    type interfaceSliceType []interface{}
    
    var interfaceAsSlice interfaceSliceType
    
    func main() {
        loop(append(interfaceAsSlice, 1, 2, 3))
        loop(append(interfaceAsSlice, "1", "2", "3"))
        // or
        loop([]interface{}{[]string{"1"}, []string{"2"}, []string{"3"}})
        fmt.Println("------------------")
    
    
        // and of course one such slice can hold any type
        loop(interfaceSliceType{"string", 999, map[int]string{3: "three"}})
    }
    
    func loop(slice []interface{}) {
        for _, elem := range slice {
            switch elemTyped := elem.(type) {
            case int:
                fmt.Println("int:", elemTyped)
            case string:
                fmt.Println("string:", elemTyped)
            case []string:
                fmt.Println("[]string:", elemTyped)
            case interface{}:
                fmt.Println("map:", elemTyped)
            }
        }
    }
    

    output:

    int: 1
    int: 2
    int: 3
    string: 1
    string: 2
    string: 3
    []string: [1]
    []string: [2]
    []string: [3]
    ------------------
    string: string
    int: 999
    map: map[3:three]
    

    try it out

提交回复
热议问题