简体   繁体   中英

Go: How to get length of slice in function?

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?

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.

As hinted in comments you would have to use reflection to do this, something like the following:

var sliceLen int

switch reflect.TypeOf(data).Kind() {

    case reflect.Slice:
        sliceLen = s.Len();
    default:
        //error here, unexpected
    }
}

Although go provides reflection to do these little tricks when you need to (as well as many other uses), it is often better to avoid wherever possible to maintain compiler type safety and performance, consider the pros/cons of having separate functions for different data types over this approach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM