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

The addCLA.go program revisited

This subsection will present an improved version of the addCLA.go program we developed in the previous chapter, to make it able to handle any kind of user input. The new program will be called addCLAImproved.go, but instead of presenting its full Go code, you will only see the differences between addCLAImproved.go and addCLA.go using the diff(1) command-line utility:

$ diff addCLAImproved.go addCLA.go
13,18c13,14
<           temp, err := strconv.Atoi(arguments[i])
<           if err == nil {
<                 sum = sum + temp
<           } else {
<                 fmt.Println("Ignoring", arguments[i])
<           }
---
>           temp, _ := strconv.Atoi(arguments[i])
>           sum = sum + temp

What this output basically tells us is that the last two lines of code, which can be found in addCLA.go and begin with the > character, were replaced by the lines of code that begin with the < character in addCLAImproved.go. The remaining code of both files is exactly the same.

The diff(1) utility compares text files line by line and is a handy way of spotting code differences between different versions of the same file.

Executing addCLAImproved.go will generate the following kind of output:

$ go run addCLAImproved.go
Sum: 0
$ go run addCLAImproved.go 1 2 -3
Sum: 0
$ go run addCLAImproved.go 1 a 2 b 3.2 @
Ignoring a
Ignoring b
Ignoring 3.2
Ignoring @
Sum: 3

So, the new and improved version works as expected, behaves reliably, and allows us to differentiate between valid and invalid input.

主站蜘蛛池模板: 石棉县| 泸定县| 巨野县| 隆尧县| 勃利县| 泰来县| 永济市| 嵩明县| 钟山县| 泉州市| 临邑县| 绥棱县| 东光县| 枣强县| 耒阳市| 南岸区| 东丰县| 平武县| 科尔| 庐江县| 安丘市| 平原县| 彭阳县| 阜阳市| 怀宁县| 绥江县| 墨竹工卡县| 闵行区| 宿松县| 万荣县| 屏东市| 英德市| 阿勒泰市| 嘉黎县| 乐都县| 玉环县| 蓝田县| 贺兰县| 信宜市| 柘城县| 芦山县|