简体   繁体   English

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

[英]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 . 但是,当我取消注释打印切片长度的行时,会出现错误,指出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. 您应尽可能避免使用interface {}。 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 . 即使执行此操作,v仍然是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. 幸运的是,Value有许多可用于转换它的方法。 In this case, v.Int() would return the value as an int64. 在这种情况下, v.Int()会将值返回为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 尽管go可以在需要时(以及许多其他用途)提供反思,以做这些小技巧,但通常最好避免尽可能保持编译器类型的安全性和性能,并考虑为不同数据提供单独功能的利弊这种方法的类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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