How to access command-line arguments passed to a Go program?

前端 未结 6 1235
夕颜
夕颜 2020-12-08 01:26

How do I access command-line arguments in Go? They\'re not passed as arguments to main.

A complete program, possibly created by linking m

6条回答
  •  清歌不尽
    2020-12-08 01:59

    Quick Answer:

    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)
    }
    

    Test: $ go run test.go 1 2 3 4 5

    Out:

    [/tmp/go-build162373819/command-line-arguments/_obj/exe/modbus 1 2 3 4 5]
    [1 2 3 4 5]
    3
    

    NOTE: os.Args provides access to raw command-line arguments. Note that the first value in this slice is the path to the program, and os.Args[1:] holds the arguments to the program. Reference

提交回复
热议问题