使用一个字段创建 Ada 记录
我定义了一种类型:
type Foo is record
bar : Positive;
end record;
我想创建一个返回记录实例的函数:
function get_foo return Foo is
return (1);
end get_foo;
但 Ada 不允许我这样做,说“位置聚合不能有一个参数”。
愚蠢地尝试,我在记录中添加了另一个哑字段,然后 return (1, DOESNT_MATTER);
有效!
我如何告诉 Ada 这不是位置聚合,而是创建记录的尝试?
I've define a type:
type Foo is record
bar : Positive;
end record;
I want to create a function that returns an instance of the record:
function get_foo return Foo is
return (1);
end get_foo;
But Ada won't let me, saying "positional aggregate cannot have one argument".
Stupidly trying, I've added another dumb field to the record, and then return (1, DOESNT_MATTER);
works!
How do I tell Ada that's not a positional aggregate, but an attempt to create a record?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
位置聚合初始化不能用于只有一个组件的记录,但这并不意味着您不能拥有只有一个组件的记录。
记录类型的值是通过给出命名字段的列表来指定的。
get_foo
函数的正确代码应如下所示。您还可以使用
Foo'(bar => 1)
表达式指定记录的类型。在实践中,使用命名组件列表比位置初始化更好。您可能会忘记该组件的位置,并且如果您在记录中添加新字段,该位置也不会改变。
The positional aggregate initialization cannot be used with record having only one component, but that does not mean you cannot have record with one component.
The values of a record type are specified by giving a list of named fields. The correct code for your
get_foo
function should be as following.You can also specify the type of the record using the
Foo'(bar => 1)
expression.Using the list of named components is better in practice than positional initilization. You can forget the position of the component and it does not change if you add a new field into your record.