对象字段的默认值

对象字段允许具有一个常量默认值。如果提供了默认值,则可以省略字段的类型。

  1. type
  2. Foo = object
  3. a: int = 2
  4. b: float = 3.14
  5. c = "I can have a default value"
  6. Bar = ref object
  7. a: int = 2
  8. b: float = 3.14
  9. c = "I can have a default value"

显式初始化使用这些默认值,包括使用对象构造表达式或过程 default 创建的 object ;使用对象构造表达式或过程 new 创建的 ref object ;具有子类型的数组或元组,该子类型使用过程 default 创建了默认值。

  1. type
  2. Foo = object
  3. a: int = 2
  4. b = 3.0
  5. Bar = ref object
  6. a: int = 2
  7. b = 3.0
  8. block: # created with an object construction expression
  9. let x = Foo()
  10. assert x.a == 2 and x.b == 3.0
  11. let y = Bar()
  12. assert y.a == 2 and y.b == 3.0
  13. block: # created with an object construction expression
  14. let x = default(Foo)
  15. assert x.a == 2 and x.b == 3.0
  16. let y = default(array[1, Foo])
  17. assert y[0].a == 2 and y[0].b == 3.0
  18. let z = default(tuple[x: Foo])
  19. assert z.x.a == 2 and z.x.b == 3.0
  20. block: # created with the procedure `new`
  21. let y = new Bar
  22. assert y.a == 2 and y.b == 3.0