Skip to content

case of

07 节 中的例子可以用 case of 等效 (๑ ꒪ꌂ꒪๑)

import std/strutils
import std/strformat

while true:
  echo "Which videocard does linux respect most?"
  let card = stdin.readLine
  let lower = card.toLower
  case lower:
    of "nvidia":
      echo &"So {card} fxxk you!"
    of "amd":
      echo "AMD YES!"
    else:
      echo "No, that's wrong!"

case of 支持范围 ദ്ദി^._.^)

1
2
3
4
5
6
7
8
from std/strutils import parseInt

echo "A number please: "
let n = parseInt(readLine(stdin))

case n:
  of 0..2, 4..7: echo "The number is in the set: {0, 1, 2, 4, 5, 6, 7}"
  of 3, 8: echo "The number is 3 or 8"

其中, , 是 或逻辑

然而, 这段代码不能通过编译: Error: not all cases are covered

没有考虑 "default" 分支, 这时候用 else:

1
2
3
  ...
  of 3, 8: echo "The number is 3 or 8"
  else: discard

当然, 如果你乐意的话, 可以这么写 (64 位平台): ╮(╯_╰)╭

  # very good range of int64, love from low(int)
  of -9223372036854775808..(-1), 9..9223372036854775807: discard