Lehirt / no_idea

0 stars 0 forks source link

Command-Line Arguments & Command-Line Flags #2

Open Lehirt opened 2 years ago

Lehirt commented 2 years ago

Command-line arguments are a common way to parameterize execution of programs. For example, go run hello.go uses run and hello.go arguments to the go program.

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.

You can get individual args with normal indexing.

To experiment with command-line arguments it’s best to build a binary with go build first.

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)
}
$ go build command-line-arguments.go
$ ./command-line-arguments a b c d
[./command-line-arguments a b c d]       
[a b c d]
c
Lehirt commented 2 years ago

Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag.

Basic flag declarations are available for string, integer, and boolean options. Here we declare a string flag word with a default value "foo" and a short description. This flag.String function returns a string pointer (not a string value); we’ll see how to use this pointer below.

This declares numb and fork flags, using a similar approach to the word flag.

It’s also possible to declare an option that uses an existing var declared elsewhere in the program. Note that we need to pass in a pointer to the flag declaration function.

Once all flags are declared, call flag.Parse() to execute the command-line parsing.

Here we’ll just dump out the parsed options and any trailing positional arguments. Note that we need to dereference the pointers with e.g. *wordPtr to get the actual option values.

To experiment with the command-line flags program it’s best to first compile it and then run the resulting binary directly.

package main

import (
    "flag"
    "fmt"
)

func main() {

    wordPtr := flag.String("word", "foo", "a string")

    numbPtr := flag.Int("numb", 42, "an int")
    forkPtr := flag.Bool("fork", false, "a bool")

    var svar string
    flag.StringVar(&svar, "svar", "bar", "a string var")

    flag.Parse()

    fmt.Println("word:", *wordPtr)
    fmt.Println("numb:", *numbPtr)
    fmt.Println("fork:", *forkPtr)
    fmt.Println("svar:", svar)
    fmt.Println("tail:", flag.Args())
}
Lehirt commented 2 years ago

引用:Go by Example Go by Example: Command-Line Flags Go by Example: Command-Line Arguments