donglu1881 2018-10-17 13:38
浏览 10
已采纳

如何在Golang中借助标志使用随机参数

I want the input from the console to be of anonymous parameters. My current way of execution is

./app -infc=eth0 -ip=192.168.0.1

I don't want this as I need this app to be universal so that I can use it for other purposes as well.

I want the CLI to be like this

./app -firstparam={{infc},eth0} -secondparam={{ip},192.168.0.1}

So this should basically work by reading the two columns in the parameters.

So it should parse the parameters as a an internal key value pair

Need help on how to store each of the parameter as a key value pair and later use them individually

  • 写回答

2条回答 默认 最新

  • douqiao6015 2018-10-17 14:42
    关注

    Here's a barebones example to give you an idea how to process os.Args

    $ go run main.go --foo asdf --bar xxx --baz ccc
    map[--foo:asdf --bar:xxx --baz:ccc]
    jsandrew-Mac:osarg jsandrew$ cat main.go
    package main
    
    import (
        "fmt"
        "os"
    )
    
    func manyRandomArg() map[string]string {
        rv := make(map[string]string)
        for ix, x := range os.Args {
            if x[:2] == "--" {
                rv[x] = os.Args[ix+1]
            }
        }
        return rv
    }
    
    func main() {
        fmt.Printf("%v
    ", manyRandomArg())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: