简体   繁体   English

将数组从索引1发送到函数

[英]Send array from index 1 to function

I've this function and and I got values which I need to use from args 我有这个功能,我从args需要使用的值

Run: func(cmd *cobra.Command, args []string) {

   ....

    myFunc(args)
} 

I need to pass to myFunc all the args from index 1 and not 0 . 我需要将index 1而不是0所有参数传递给myFunc of course I can loop and create another array from index 1 but this duplicate almost all the values except index 0 , is there a way to avoid it in GO? 当然,我可以循环并从索引1创建另一个数组,但是该副本几乎复制了除索引0以外的所有值,有没有一种方法可以避免它在GO中出现?

Yes, simply slice the args slice, and pass that: 是的,只要args片,并通过如下:

myFunc(args[1:])

args is a slice , not an array . args切片 ,而不是数组 You can (re-)slice slices, which will be a contiguous subpart of the original slice. 您可以(重新)切片切片,这将是原始切片的连续子部分。 For example: 例如:

args[1:4]

The above would be another slice, holding only the following elements from args : 上面是另一个切片,仅包含args的以下元素:

args[1], args[2], args[3]

The upper limit is exclusive. 上限是排他的。 A missing upper index defaults to the length, a missing lower index defaults to 0 . 缺少的上层索引默认为长度,缺少的下层索引默认为0 These are all detailed in Spec: Slice expressions . 这些都在Spec:Slice表达式中进行了详细说明。

Note that slicing a slice does not copy the elements: it will point to the same underlying array which actually holds the elements. 请注意,对切片进行切片不会复制元素:它将指向实际包含元素的同一基础数组。 A slice is just a small, struct-like header containing a pointer to the underlying array. 切片只是一个小的,类似于结构的标头,其中包含指向基础数组的指针。

Note that if args is empty, the above would result in a run-time panic. 请注意,如果args为空,则上述操作会导致运行时出现紧急情况。 To avoid that, first check its length: 为避免这种情况,请首先检查其长度:

if len(args) == 0 {
    myFunc(nil) // or an empty slice: []string{}
} else {
    myFunc(args[1:])
}

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

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