第一种写法 —— switch x
注意:switch会自动break,除非使用fallthrough
func branch(a, b int, op string) int { var result int switch op { case "+": result = a + b case "-": result = a - b case "*": result = a * b case "/": result = a / b default: panic("unexpected op:" + op) } fmt.Println(result) return result }
第二种写法 —— switch后直接写花括号
func grade(score int) string { g := "" switch { case score < 0 || score > 100: panic(fmt.Sprintf( "Wrong score: %d", score)) case score < 60: g = "F" case score < 80: g = "C" case score < 90: g = "B" case score <= 100: g = "A" } return g }
- 本文固定链接: https://weiguangli.com/archives/211
- 转载请注明: lwg0452 于 Weiguang的博客 发表
捐 赠如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!