- Go Systems Programming
- Mihalis Tsoukalos
- 428字
- 2021-07-02 18:07:57
Getting user input
Apart from using command-line arguments to get user input, which is the preferred approach in systems programming, there exist ways to ask the user for input.
Two such examples are the rm(1) and mv(1) commands when used with the -i option:
$ touch aFile $ rm -i aFile remove aFile? y $ touch aFile $ touch ../aFile $ mv -i ../aFile . overwrite ./aFile? (y/n [n]) y
So, this section will show you how to mimic the previous behavior in your Go code by making your program understand the -i parameter without actually implementing the functionality of either rm(1) or mv(1).
The simplest function for getting user input is called fmt.Scanln() and reads an entire line. Other functions for getting user input include fmt.Scan(), fmt.Scanf(), fmt.Sscanf(), fmt.Sscanln(), and fmt.Sscan().
However, there exists a more advanced way to get input from the user in Go; it involves the use of the bufio package. Nevertheless, using the bufio package to get a simple response from a user is a bit of an overkill.
The Go code of parameter.go is as follows:
package main import ( "fmt" "os" "strings" ) func main() { arguments := os.Args minusI := false for i := 0; i < len(arguments); i++ { if strings.Compare(arguments[i], "-i") == 0 { minusI = true break } } if minusI { fmt.Println("Got the -i parameter!") fmt.Print("y/n: ") var answer string fmt.Scanln(&answer) fmt.Println("You entered:", answer) } else { fmt.Println("The -i parameter is not set") } }
The presented code is not particularly clever. It just visits all command-line arguments using a for loop and checks whether the current argument is equal to the -i string. Once it finds a match with the help of the strings.Compare() function, it changes the value of the minusI variable from false to true. Then, as it does not need to look any further, it exits the for loop using a break statement. In case the -i parameter is given, the block with the if statement asks the user to enter y or n using the fmt.Scanln() function.
Note that the fmt.Scanln() function uses a pointer to the answer variable. Since Go passes its variables by value, we have to use a pointer reference here in order to save the user input to the answer variable. Generally speaking, functions that read data from the user tend to work this way.
Executing parameter.go creates the following kind of output:
$ go run parameter.go The -i parameter is not set $ go run parameter.go -i Got the -i parameter! y/n: y You entered: y
- SPSS數據挖掘與案例分析應用實踐
- ClickHouse性能之巔:從架構設計解讀性能之謎
- PHP 從入門到項目實踐(超值版)
- Web Development with Django Cookbook
- Java程序員面試算法寶典
- Python面向對象編程:構建游戲和GUI
- Protocol-Oriented Programming with Swift
- Python語言科研繪圖與學術圖表繪制從入門到精通
- Clojure for Java Developers
- Hadoop大數據分析技術
- 奔跑吧 Linux內核
- Java EE 8 and Angular
- MongoDB Cookbook
- PostgreSQL 12 High Availability Cookbook
- 計算機應用基礎(Windows 7+Office 2010)