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

  • Go Systems Programming
  • Mihalis Tsoukalos
  • 321字
  • 2021-07-02 18:08:02

Creating summaries

In this section, we will develop a program that adds all the values of a given column of text with multiple lines. To make things even more interesting, the column number will be given as a parameter in the program. The main difference between the program of this subsection and readColumn.go from the previous subsection is that you will need to convert each value into an integer number.

The name of the program that will be developed is summary.go and can be divided into three parts.

The first part is this:

package main 
 
import ( 
   "fmt" 
   "os" 
   "strconv" 
   "strings" 
) 
 
func main() { 
   var s [3]string 
   s[0] = "1 b 3" 
   s[1] = "11 a 1 14 1 1" 
   s[2] = "-1 2 -3 -4 -5" 

The second part has the following Go code:

   arguments := os.Args 
   column, err := strconv.Atoi(arguments[1]) 
   if err != nil { 
         fmt.Println("Error reading argument") 
         os.Exit(-1) 
   } 
   if column == 0 { 
         fmt.Println("Invalid column") 
         os.Exit(1) 
   } 

The previous code reads the index of the column that interests you. If you want to make summary.go even better, you can check for negative values in the column variable and print the appropriate error message.

The last part of summary.go is as follows:

   sum := 0 
   for i := 0; i < len(s); i++ { 
         data := strings.Fields(s[i]) 
         if len(data) >= column { 
               temp, err := strconv.Atoi(data[column-1]) 
               if err == nil { 
                     sum = sum + temp 
               } else { 
                     fmt.Printf("Invalid argument: %s\n", data[column-1]) 
               } 
         } else { 
               fmt.Println("Invalid column!") 
         } 
   } 
   fmt.Printf("Sum: %d\n", sum) 
} 

As you can see, most of the Go code in summary.go is about dealing with exceptions and potential errors. The core functionality of summary.go is implemented in a few lines of Go code.

Executing summary.go will give you the following output:

$ go run summary.go 0
Invalid column
exit status 1
$ go run summary.go 2
Invalid argument: b
Invalid argument: a
Sum: 2
$ go run summary.go 1
Sum: 11
主站蜘蛛池模板: 天镇县| 汝阳县| 浑源县| 新闻| 宣恩县| 都兰县| 黄石市| 康马县| 汾西县| 邵武市| 贵港市| 赫章县| 玉田县| 巴林右旗| 安阳县| 剑河县| 防城港市| 石首市| 方山县| 任丘市| 友谊县| 如皋市| 鄂托克旗| 阿拉善左旗| 叙永县| 茂名市| 慈溪市| 福海县| 金昌市| 锦屏县| 泊头市| 奈曼旗| 廉江市| 收藏| 华安县| 凤凰县| 阿勒泰市| 乐昌市| 大关县| 锡林郭勒盟| 涟源市|