官术网_书友最值得收藏!

Using command-line arguments

Command-line arguments allow your programs to get input, such as the names of the files you want to process, without having to write a different version of the program. Hence, you cannot create any useful systems software if you're unable to process the command-line arguments passed to it.

So here is a naive Go program, named cla.go, that prints all its command-line arguments, including the name of the executable file:

package main 
 
import "fmt" 
import "os" 
 
func main() { 
   arguments := os.Args 
   for i := 0; i < len(arguments); i++ { 
         fmt.Println(arguments[i]) 
   } 
} 

As you can see, Go needs an extra package named os in order to read the command-line arguments of a program that are stored in the os.Args array. In case you do not like having multiple import statements, you can rewrite the two import statements as follows, which I find much easier to read:

import ( 
   "fmt" 
   "os" 
)
The gofmt utility puts package names in alphabetical order when you are importing all your packages using a single import block.

The Go code of cla.go is simple as it stores all the command-line arguments in an array and uses a for loop for printing them. As you will see in forthcoming chapters, the os package can do many more things. If you are familiar with C, you should know that in C, command-line arguments are automatically passed to programs, and you do not need to include any extra header files in order to read them. Go uses a different approach that gives you more control but requires slightly more code.

Executing cla.go after building it first will create the following kind of output:

$ ./cla 1 2 three
./cla
1
2
three
主站蜘蛛池模板: 黄石市| 资阳市| 江永县| 博湖县| 拉孜县| 左贡县| 花莲县| 兴仁县| 綦江县| 柳林县| 文昌市| 木兰县| 冕宁县| 句容市| 留坝县| 滕州市| 广州市| 平昌县| 台东县| 越西县| 大埔区| 芜湖县| 香格里拉县| 五莲县| 彝良县| 尼木县| 红河县| 武城县| 栖霞市| 响水县| 华安县| 东平县| 祁门县| 南陵县| 巴彦淖尔市| 丰顺县| 光山县| 济宁市| 永新县| 微山县| 丹东市|