Go command line parameters and standard input and output
tags (space delimited): Go 1.Go command line parameters are stored in the slice OS using the GO command line parameter. Args, which can be said to be very similar to the command line parameters of Python
Fmt. Println (OS. Args)//Print the slice contents for
I: = 0; i < len (OS. Args); i++ {
FMT. Println (OS. Args[i])
}
The first parameter is the name of the executable file, and the other parameters are stored as strings in the slice OS. In args, all parameters can be traversed by the for Range statement
For I, args: = Range os. Args {
FMT. Printf ("args[%d]=%s\n", I,args)
2. Flag Packet parsing of command-line argumentsThe above parameter parsing only stores parameters from the command business in the OS. In the args slice, the application is not very convenient, especially, the compiled executable file, when others do not know how to use, you can use the go built-in flag package to explain the parameters, and can set the default values. How to use the flag package
Flag. Type ("FlagName", DefaultValue, "help message") *type
The flag package sets the default value and help information for the flag FlagName, depending on the type, and the parameter flag FlagName, and eventually returns a pointer to that type, which is an example of whether the flag parameter is used in the command line by whether the pointer is empty or not.
Import (
"flag"
"FMT"
)
var n = flag. Int ("n", 1, "Number of page")
var s = flag. String ("s", "nothing", "info")
func Main () {
flag. Parse ()
FMT. Println (*n)
FMT. Println (*s)
}
Execute./CMD–HELP can see the parameter Help information set
The parameter settings are typically used in the INIT function before the main function starts, so that you can use 3 directly in the main function . Standard input and output
Standard input and output, commonly used in normal procedures, general reading, printing, etc.
Reading data from standard input
Func Main () {
input: = Bufio. Newscanner (OS. Stdin)//Initializes a sweep table object for
input. Scan () {//Scanning input line
: = input. Text ()//convert the input to a string
fmt. PRINTLN (line)//output to standard output
}
}