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

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题