typeof 运算符

注意: 由于历史原因 typeof(x) 也可写作 type(x) ,但是不鼓励这种写法。

取给定的表达式的 typeof 值就能得到这个表达式的类型(在其它的很多语言里这被称为 typeof 运算符):

  1. var x = 0
  2. var y: typeof(x) # y 的类型是 int

如果 typeof 被用来判断函数(或迭代器、变换器)调用 c(X) 的结果的类型(这里,X 代表可能为空的参数列表), 解释代码时,与其它方式相比,优先考虑把 c 视作迭代器。通过给 typeof 传入第二个参数 typeOfProc 可以改变这种行为。

  1. iterator split(s: string): string = discard
  2. proc split(s: string): seq[string] = discard
  3. # 因为迭代器是首选的解释,所以它的类型是 `string` :
  4. assert typeof("a b c".split) is string
  5. assert typeof("a b c".split, typeOfProc) is seq[string]