Creating Ada record with one field

可紊 提交于 2019-12-23 09:36:57

问题


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?


回答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.

function get_foo return Foo is
    return (bar => 1);
end get_foo;

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.



来源:https://stackoverflow.com/questions/2743099/creating-ada-record-with-one-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!