对象构造

对象也可以使用 object construction expression “对象构建表达式” 创建, 即以下语法 T(fieldA: valueA, fieldB: valueB, …) 其中 T 是 object 类型或 ref object 类型:

  1. type
  2. Student = object
  3. name: string
  4. age: int
  5. PStudent = ref Student
  6. var a1 = Student(name: "Anton", age: 5)
  7. var a2 = PStudent(name: "Anton", age: 5)
  8. # 这样也可以直接构造:
  9. var a3 = (ref Student)(name: "Anton", age: 5)
  10. # 不必提到所有字段,而且这些字段可以是乱序的:
  11. var a4 = Student(age: 5)

请注意,与元组不同,对象需要字段名称及其值。对于 ref object 类型,隐式调用 system.new 。