最近看由人民邮电出版社许式伟 吕桂华等编著《Go语言编程》【第1章初识Go语言】【1.5 工程管理】时,发现了示例代码calc.go有几处错误,args := os.Args数组变量args[0]代表程序自身,3个if语句len(args)条件判断右值也都小了1,按照书本编写代码运行时将会一直执行匿名函数Usage(),显示如下:
USAGE: calc command [arguments] ...
The commands are:
add Addition of two values.
sqrt Square root of a non-negative value.
正确的calc.go代码如下:
// calc.go
package main
import (
"fmt"
"os"
"simplemath"
"strconv"
)
var Usage = func() {
fmt.Println("USAGE: calc command [arguments] ...")
fmt.Println("\nThe commands are:\n\tadd\tAddition of two values.\n\tsqrt\tSquare root of a non-negative value.")
}
func main() {
args := os.Args
if args == nil || len(args) < 3 {
Usage()
return
}
switch args[1] {
case "add":
if len(args) != 4 {
fmt.Println("USAGE: calc add <integer1><integer2>")
return
}
v1, err1 := strconv.Atoi(args[2])
v2, err2 := strconv.Atoi(args[3])
if err1 != nil || err2 != nil {
fmt.Println("USAGE: calc add <integer1><integer2>")
return
}
ret := simplemath.Add(v1, v2)
fmt.Println("Result: ", ret)
case "sqrt":
if len(args) != 3 {
fmt.Println("USAGE: cale sqrt <integer>")
return
}
v, err := strconv.Atoi(args[2])
if err != nil {
fmt.Println("USAGE: calc sqrt <integer>")
return
}
ret := simplemath.Sqrt(v)
fmt.Println("Result: ", ret)
default:
Usage()
}
}
本文出自 “松松” 博客,请务必保留此出处http://dongsong.blog.51cto.com/916653/1587144
原文地址:http://dongsong.blog.51cto.com/916653/1587144