- Go Systems Programming
- Mihalis Tsoukalos
- 289字
- 2021-07-02 18:07:57
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 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
- MySQL 8從入門到精通(視頻教學版)
- Java技術手冊(原書第7版)
- Microsoft System Center Orchestrator 2012 R2 Essentials
- SSM輕量級框架應用實戰
- Nginx實戰:基于Lua語言的配置、開發與架構詳解
- RESTful Java Web Services(Second Edition)
- 用戶體驗可視化指南
- Swift語言實戰晉級
- Instant Apache Camel Messaging System
- Drupal 8 Development:Beginner's Guide(Second Edition)
- After Effects CC技術大全
- HTML并不簡單:Web前端開發精進秘籍
- R High Performance Programming
- Python編程零基礎入門
- Instant JRebel