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

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
主站蜘蛛池模板: 根河市| 铜陵市| 佛冈县| 平凉市| 泰来县| 十堰市| 定西市| 隆尧县| 大渡口区| 巴彦淖尔市| 临夏市| 行唐县| 天全县| 丰都县| 马公市| 额尔古纳市| 新巴尔虎右旗| 石棉县| 龙江县| 新野县| 汽车| 商河县| 吴忠市| 盐源县| 班玛县| 乡宁县| 徐水县| 和田县| 寿阳县| 黄山市| 婺源县| 渭源县| 错那县| 衡阳县| 林口县| 军事| 正定县| 达孜县| 民县| 天镇县| 论坛|