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

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.

主站蜘蛛池模板: 西青区| 江口县| 石林| 旬阳县| 石屏县| 乐陵市| 顺昌县| 阿克陶县| 张掖市| 蕲春县| 威宁| 梁平县| 诸暨市| 东丰县| 盐池县| 鱼台县| 辽源市| 永定县| 漯河市| 财经| 孟津县| 定州市| 高州市| 崇州市| 阿拉善右旗| 大关县| 呼图壁县| 永宁县| 卢龙县| 长治市| 漳州市| 崇礼县| 丰宁| 澄城县| 景洪市| 马关县| 中方县| 翼城县| 漠河县| 通辽市| 曲麻莱县|