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

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.

主站蜘蛛池模板: 崇阳县| 聊城市| 新疆| 广东省| 河北省| 财经| 华宁县| 安仁县| 正蓝旗| 兴山县| 巴楚县| 淮阳县| 乌兰浩特市| 呼伦贝尔市| 织金县| 金山区| 渝中区| 阜南县| 商城县| 榆林市| 凤台县| 台山市| 和政县| 启东市| 佛冈县| 隆子县| 米泉市| 大理市| 墨竹工卡县| 汉沽区| 鸡西市| 顺昌县| 石台县| 永登县| 布拖县| 鹤山市| 驻马店市| 徐闻县| 阳泉市| 山西省| 兴仁县|