number, err := strconv.Atoi(arguments[1])if err !=nil { fmt.Println("The value is not an integer",number) }else {switch {case number<0: fmt.Println("Less than zero")case number >0: fmt.Println("Bigger than zero")default: fmt.Println("Zero") } }
第三部分代码:
asString := arguments[1]switch asString{case"5": fmt.Println("Five")case"0": fmt.Println("Zero")default: fmt.Println("Do not care") }
这部分代码说明case子句可以包含硬编码的变量,这种情况通常是switch`后跟有一个变量。
第四部分代码:
var negative = regexp.MustCompile(`-`)var floatingPoint = regexp.MustCompile(`\d?\.\d`)var mail = regexp.MustCompile(`^[^@]+@[^@.]+\.[^@.]+`)switch {case negative.MatchString(asString): fmt.Println("Negative number")case floatingPoint.MatchString(asString): fmt.Println("Floating Point")case mail.MatchString(asString): fmt.Println("It is an email")fallthroughdefault: fmt.Println("Something else") }
$ go run switch.go
Usage: switch number
exit status 1
hanshanjiedeMacBook-Pro:chapter4 hanshanjie$ go run switch.go mike@g.com
The value is not an integer 0
Do not care
It is an email
Something else
It is a nil interface
hanshanjiedeMacBook-Pro:chapter4 hanshanjie$ go run switch.go 5
Bigger than zero
Five
Something else
It is a nil interface
hanshanjiedeMacBook-Pro:chapter4 hanshanjie$ go run switch.go 0
Zero
Zero
Something else
It is a nil interface
hanshanjiedeMacBook-Pro:chapter4 hanshanjie$ go run switch.go 1.2
The value is not an integer 0
Do not care
Floating Point
It is a nil interface
hanshanjiedeMacBook-Pro:chapter4 hanshanjie$ go run switch.go -1.5
The value is not an integer 0
Do not care
Negative number
It is a nil interface