douao1858 2015-11-15 15:50
浏览 15
已采纳

将命名参数传递给Golang工具并使用它们的最简洁方法是什么?

Aim: to pass named arguments to a Golang tool and to use the passed arguments as variables


Attempt

Compiling the following example:

package main

import (
  "fmt"
  "os"
)

func main() {
  argsWithProg := os.Args
  argsWithoutProg := os.Args[1:]
  arg := os.Args[3]

  fmt.Println(argsWithProg)
  fmt.Println(argsWithoutProg)
  fmt.Println(arg)
}

build it and pass arguments, e.g.: ./args -a=1 -b=2 -c=3 -d=4 -e=5 -f=6, results in:

[./args -a=1 -b=2 -c=3 -d=4 -e=5 -f=6]
[-a=1 -b=2 -c=3 -d=4 -e=5 -f=6]
-c=3

Based on this answer, the following snippet was added to the example:

s := strings.Split(arg, "=")
variable, value := s[0], s[1]
fmt.Println(variable, value)

and after building it and passing arguments the output is as follows:

[./args -a=1 -b=2 -c=3 -d=4 -e=5 -f=6]
[-a=1 -b=2 -c=3 -d=4 -e=5 -f=6]
-c=3
-c 3

Question

Although the aim has been accomplished I wonder whether this is the most concise way to pass named arguments and to use them in Golang.

  • 写回答

1条回答 默认 最新

  • dsbgltg159136540 2015-11-15 15:55
    关注

    Package flag

    import "flag" 
    

    Package flag implements command-line flag parsing.

    Try the flag and other similar packages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP