Passing CLI arguments to excutables with 'go run'

前端 未结 2 446
无人共我
无人共我 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

    You can use -- to separate gofiles from arguments:

    go run readfile.go -- readfile.go
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题