Golang is a fast, efficient and reliable programming language, and flag.Arg(0) is a commonly used function in Golang, used to return the parameters passed by exec.cmd Index 1. However, PHP editor Zimo pointed out that the behavior of this function is not as expected, and it actually returns index 1 instead of index 0. This problem may cause errors in the processing of parameters by the program. In this article, we will explain the cause of this problem and provide solutions to help developers use the flag.Arg(0) function correctly.
I have some content in my current bar
application that looks like this
flag.parse() str := flag.arg(0) fmt.println(str)
Now in my foo application I have something like this
var stdout, stderr bytes.Buffer cmd := exec.Cmd{ Path: c.Path, Args: c.Args, Env: c.Env, Stdin: bytes.NewReader(b), Stdout: &stdout, Stderr: &stderr, } if err := cmd.Start(); err != nil { return err }
Now c.args above = [1,2,3]
foo program tries to call bar program, bar displays 2 How to make the column display 1.
I know flag.parse
Ignore the first parameter. How to read the first argument (index 0) using flag.arg()
cmd.args
Contains the command name. flag.arg(0)
is the first argument after the command name and flag.
Fixed by adding the command name to cmd.args
.
cmd := exec.Cmd{ Path: c.Path, Args: append([]string{c.Path}, c.Args...), Env: c.Env, Stdin: bytes.NewReader(b), Stdout: &stdout, Stderr: &stderr, }
The above is the detailed content of Golang - flag.Arg(0) returns index 1 of the argument passed by exec.cmd instead of index 0. For more information, please follow other related articles on the PHP Chinese website!