Passing CLI arguments to excutables with 'go run'

前端 未结 2 450
无人共我
无人共我 2021-02-13 13:48

I have a program readfile.go and I want to give the command line argument os.Args[1] also as readfile.go.

However \'go run\' thinks

2条回答
  •  南笙
    南笙 (楼主)
    2021-02-13 14:28

    To avoid the ambiguity of getting twice readfile.go, I advise you to use named flags. This will solve the problem too.

    Example:

    package main
    
    import (
        "flag"
        "fmt"
    )
    
    func main() {
        cmd := flag.String("cmd", "", "")
        flag.Parse()
        fmt.Printf("my cmd: \"%v\"\n", string(*cmd))
    }
    

    Don't forget using flag.Parse() to retrieve the command line arguments

    You can pass args to the go run command this way: go run .\main.go -cmd main.go and you'll get as output:

    my cmd: "main.go"
    

    I hope this can help other.

提交回复
热议问题