对象字段的默认值
对象字段允许具有一个常量默认值。如果提供了默认值,则可以省略字段的类型。
type
Foo = object
a: int = 2
b: float = 3.14
c = "I can have a default value"
Bar = ref object
a: int = 2
b: float = 3.14
c = "I can have a default value"
显式初始化使用这些默认值,包括使用对象构造表达式或过程 default 创建的 object ;使用对象构造表达式或过程 new 创建的 ref object ;具有子类型的数组或元组,该子类型使用过程 default 创建了默认值。
type
Foo = object
a: int = 2
b = 3.0
Bar = ref object
a: int = 2
b = 3.0
block: # created with an object construction expression
let x = Foo()
assert x.a == 2 and x.b == 3.0
let y = Bar()
assert y.a == 2 and y.b == 3.0
block: # created with an object construction expression
let x = default(Foo)
assert x.a == 2 and x.b == 3.0
let y = default(array[1, Foo])
assert y[0].a == 2 and y[0].b == 3.0
let z = default(tuple[x: Foo])
assert z.x.a == 2 and z.x.b == 3.0
block: # created with the procedure `new`
let y = new Bar
assert y.a == 2 and y.b == 3.0
当前内容版权归 vectorworkshopbaoerjie 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 vectorworkshopbaoerjie .