diff --git a/base/switch/main.go b/base/switch/main.go new file mode 100644 index 0000000..20eaccf --- /dev/null +++ b/base/switch/main.go @@ -0,0 +1,72 @@ +package main + +import ( + "fmt" + "math/rand" + "time" +) + +func main() { + // 设置随机数种子 + seed := rand.NewSource(time.Now().UnixNano()) + r := rand.New(seed) + + for i := 0; i < 5; i++ { + // 写法一 + switch t := r.Intn(100); t / 10 { + case 0, 1, 2: + fmt.Println("t 在 [ 0~30) 之间", t) + case 3, 4, 5: + fmt.Println("t 在 [30~50) 之间", t) + // fallthrough 类似 C语言中 没有添加 break 的情况 继续往下执行 + fallthrough + + case 6, 7, 8: + if t < 60 { + fmt.Println("6? || 7? || 8? 这不是你该来的地方") + } else { + fmt.Println("t 在 [60~90) 之间", t) + } + fallthrough + case 9: + if t < 90 { + fmt.Println("9? 这不是你该来的地方") + } else { + fmt.Println("t 在 [90~100) 之间", t) + } + fallthrough + default: + fmt.Println("至少 t 是一个数字 => ", t) + } + + fmt.Println("=========================================================") + + // 写法二 表达式 + switch t := r.Intn(100); { + case t < 30: + fmt.Println("t 在 [ 0~30) 之间", t) + case t < 50: + fmt.Println("t 在 [30~50) 之间", t) + fallthrough + case t < 80: + if t < 60 { + fmt.Println("6? || 7? || 8? 这不是你该来的地方") + } else { + fmt.Println("t 在 [60~90) 之间", t) + } + fallthrough + case t < 100: + if t < 90 { + fmt.Println("9? 这不是你该来的地方") + } else { + fmt.Println("t 在 [90~100) 之间", t) + } + fallthrough + default: + fmt.Println("至少 t 是一个数字 => ", t) + } + + fmt.Println("=========================================================") + } + +}