使用一个字段创建Ada记录 [英] Creating Ada record with one field
问题描述
我定义了一个类型:
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;
但是Ada不会让我说位置合计不能有一个论点。
愚蠢地尝试,我在记录中添加了另一个哑字段,然后 return(1,DOESNT_MATTER);
起作用!
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!
我如何告诉Ada不是位置汇总,而是尝试创建记录?
How do I tell Ada that's not a positional aggregate, but an attempt to create a record?
推荐答案
位置聚合初始化不能用于只有一个成分的记录,但这并不意味着您不能具有一个成分的记录。
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.
记录类型的值是通过给出命名字段列表来指定。 get_foo
函数的正确代码应如下所示。
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;
还可以使用 Foo'(bar => 1)
表达式。
实际上,使用命名组件列表要比位置初始化更好。您可以忘记组件的位置,并且如果在记录中添加新字段,该位置也不会改变。
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.
这篇关于使用一个字段创建Ada记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!