标签: flag-go

如何在golang中先提供命令行参数,然后提供标志?

如果提供的输入采用以下形式,Golang 的标志包会正确读取命令行标志和参数:go run main.go -o filename.txt arg1 arg2

但如果我尝试提供像 : 这样的输入go run main.go arg1 arg2 -o filename.txt,则 main.go 之后的所有内容都会被读取为参数。

如何让这种风格发挥作用?

我的程序:

package main

import (
    "flag"
    "fmt"
)

func main() {

    var output string
    flag.StringVar(&output, "o", "", "Writes output to the file specified")
    flag.Parse()
    fmt.Println("Positional Args : ", flag.Args())
    fmt.Println("Flag -o : ", output)
}
Run Code Online (Sandbox Code Playgroud)

go run main.go -o filename.txt arg1 arg2

输出:

Positional Args :  [arg1 arg2]
Flag -o :  filename.txt
Run Code Online (Sandbox Code Playgroud)

go run main.go arg1 arg2 …

go flag-go

5
推荐指数
1
解决办法
1920
查看次数

标签 统计

flag-go ×1

go ×1