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

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
主站蜘蛛池模板: 铅山县| 大同市| 达孜县| 平原县| 嘉义市| 承德市| 新宾| 积石山| 宽城| 灵山县| 射阳县| 江山市| 开原市| 徐汇区| 保德县| 洛宁县| 铜山县| 碌曲县| 砚山县| 湘阴县| 茌平县| 湾仔区| 河源市| 龙江县| 筠连县| 柯坪县| 沅江市| 大港区| 长垣县| 堆龙德庆县| 平果县| 波密县| 中宁县| 凌海市| 宁陵县| 全州县| 秦安县| 买车| 天镇县| 东乌珠穆沁旗| 荣成市|