我的第一个想法是“不,这行不通”。但后来我用 GNAT GPL 2012 写了这个:
with Text_IO; use Text_IO;
procedure Ren_Test is
type Shared_Array is array (Integer range 1 .. 10) of Integer;
Array1 : Shared_Array := (others => 42);
Array2 : Shared_Array renames Array1(1..5);
begin
Put_Line("Array1 range: " & Integer'Image(Array1'First) & " .."
& Integer'Image(Array1'Last));
Put_Line("Array2 range: " & Integer'Image(Array2'First) & " .."
& Integer'Image(Array2'Last));
New_Line;
Put_Line("Dump Array1");
for I in Array1'Range loop
Put(Integer'Image(Array1(I)));
if I /= Array1'Last then
Put(",");
end if;
end loop;
New_Line(2);
Put_Line("Dump and modify renaming Array2");
for I in Array2'Range loop
Put(Integer'Image(Array2(I)));
if I /= Array2'Last then
Put(",");
end if;
Array1(I) := Array1(I) + 17;
end loop;
New_Line(2);
Put_Line("Redump Array1");
for I in Array1'Range loop
Put(Integer'Image(Array1(I)));
if I /= Array1'Last then
Put(",");
end if;
end loop;
New_Line;
end Ren_Test;
运行它让我:
[35] Marc say: ./ren_test
Array1 range: 1 .. 10
Array2 range: 1 .. 5
Dump Array1
42, 42, 42, 42, 42, 42, 42, 42, 42, 42
Dump and modify renaming Array2
42, 42, 42, 42, 42
Redump Array1
59, 59, 59, 59, 59, 42, 42, 42, 42, 42
我会说我对此并不满意,主要是因为我预计将约束数组切片到小于其声明大小时会出现 Constraint_Error。所以我不知道这是合法代码,我知道 GNAT GPL 2012 可以毫无问题地编译和运行它。
当 Shared_Array 是一个不受约束的数组时,我会舒服得多:
type Shared_Array is array (Integer range <>) of Integer;
Array1 : Shared_Array (1..10) := (others => 42);
Array2 : Shared_Array renames Array1(1..5);
后者我希望符合标准。第一个,受约束的形式......恕我直言,不确定。(但我会把它留给语言律师来验证这一点。)