This is a creation in Article, where the information may have evolved or changed.
Reprint: http://c2pblog.sinaapp.com/archives/349
Golang is primarily used for server-side, so the shell commands the following compile run is very important. After setting up the Golang environment under Linux, we need to use the shell to control the go language. The person familiar with the shell should know that when running the shell script, there will always be the case of substituting parameters, the general format is SH test.sh [param ...] that is, add the parameters in the back. So, no accident, go can be used in this way. Of course it's possible. And the focus of this article is to compile and run Golang with parameters.
This effect is achieved by the OS package. Os. Args [] is an array, the length is not fixed, the default length is 1, save the go run test.go such a string, so if we look forward to add parameters and call, then that is the OS. Append and read after Args. Look at the code first:
Package Main
Import (
"FMT"
"OS")
Func Main () {
Param1:=os. ARGS[1]
Param2:=os. ARGS[2]
FMT. Println (PARAM1,PARAM2)
}
The above file is saved as test.go , run go run Test.go 1 2 output 1 2
So we can parse the parameters. It looks simple, but there's a serious problem here: What if I don't have input parameters? What if the input parameter is less than the required number of parameters? What do I do if I have an extra parameter number? The same error occurs on the first two issues above: Index out of range, and the third problem discards the third argument directly. These are all things we don't want to see, so we have to do the verification. Someone said, "Never trust the user's input!" "It is intended to remind us that we need to be well-tested in dealing with any and all user interactions in case of irreparable errors. So what are we going to do? The way I found it was to rely on Len (OS). Args) to make judgments. Before getting the parameter, we should judge whether there are any parameters, if there are parameters to do the related operation, there are no parameters to make the corresponding prompt.
package main
Import (
" FMT "
" OS ")
Func Main () {
If Len (OS. Args) >1{
Param1:=os. ARGS[1]
If Len (OS. Args) ==3{
Param1:=os. ARGS[1]
Param2:=os. ARGS[2]
}
FMT. Println (PARAM1,PARAM2)
} else {
Fmt. Println ("Required parameters")
}
}
This will ensure that the array is not out of bounds