dqnk57224 2018-08-08 03:22
浏览 3
已采纳

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

I've this function and and I got values which I need to use from 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. 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条回答 默认 最新

  • dosrmo0442 2018-08-08 03:23
    关注

    Yes, simply slice the args slice, and pass that:

    myFunc(args[1:])
    

    args is a slice, not an array. 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[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. These are all detailed in Spec: Slice expressions.

    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. To avoid that, first check its length:

    if len(args) == 0 {
        myFunc(nil) // or an empty slice: []string{}
    } else {
        myFunc(args[1:])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部