douzhi8488 2017-09-06 17:38
浏览 105
已采纳

去:如何获取函数中的切片长度?

I've got a function to which I want to feed different kinds of slices after which I want to loop over them and print their contents. The following code works:

func plot(data interface{}){
    fmt.Println(data)
    //fmt.Println(len(data))
}

func main() {
    l := []int{1, 4, 3}
    plot(l)
}

But when I uncomment the line in which I print the length of the slice, I get an error saying invalid argument data (type interface {}) for len.

Any idea how I would be able to get the length of the slice so that I can loop over it?

  • 写回答

2条回答 默认 最新

  • dtoq41429 2017-09-06 17:58
    关注

    You should try to avoid using interface{} whenever possible. What you want to do can be done with reflection, but reflection is a necessary evil. It is really good for marshalling, but should be used sparingly. If you still want to use reflect, you can do something like this:

    func plot(data interface{}) {
        s := reflect.ValueOf(data)
        if s.Kind() != reflect.Slice {
            panic("plot() given a non-slice type")
        }
    
        for i := 0; i < s.Len(); i++ {
            v := s.Index(i)
            ...
        }
    }
    

    Even after doing this, v is a reflect.Value. You will then need to somehow convert that to something useful. Luckily, Value has many methods that can be used to convert it. In this case, v.Int() would return the value as an int64.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?