dqnk57224 2018-08-08 11: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 11: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:])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码