Skip to content

Commit 4c982a4

Browse files
ntreldlang-bot
authored andcommitted
[spec/expression.dd] Improve slice -> static array examples
Split function call example into two. Inline function calls for first example. Explain runtime slice conversion to SA and add example.
1 parent b010dd9 commit 4c982a4

File tree

1 file changed

+28
-17
lines changed

1 file changed

+28
-17
lines changed

spec/expression.dd

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1466,48 +1466,59 @@ $(H3 $(LNAME2 slice_to_static_array, Slice Conversion to Static Array))
14661466
-------------
14671467

14681468
If both $(CODE a) and $(CODE b) are integers (which may be constant-folded),
1469-
the slice expression can be converted to a static array type
1469+
the slice expression can be converted to a static array of type
14701470
$(D T[b - a]).
14711471

1472+
$(SPEC_RUNNABLE_EXAMPLE_RUN
1473+
---
1474+
int[] arr = [1, 2, 3];
1475+
int[2] sa = arr[1 .. 3];
1476+
1477+
assert(sa == [2, 3]);
1478+
//sa = arr[0 .. 3]; // error, cannot match length
1479+
---
1480+
)
1481+
14721482
$(SPEC_RUNNABLE_EXAMPLE_RUN
14731483
-------------
1474-
void foo(int[2] a)
1475-
{
1476-
assert(a == [2, 3]);
1477-
}
14781484
void bar(ref int[2] a)
14791485
{
14801486
assert(a == [2, 3]);
1481-
a[0] = 4;
1482-
a[1] = 5;
1483-
assert(a == [4, 5]);
1487+
a = [4, 5];
14841488
}
1485-
void baz(int[3] a) {}
14861489

14871490
void main()
14881491
{
14891492
int[] arr = [1, 2, 3];
14901493

1491-
foo(arr[1 .. 3]);
1492-
assert(arr == [1, 2, 3]);
1493-
1494+
// slicing an lvalue gives an lvalue
14941495
bar(arr[1 .. 3]);
14951496
assert(arr == [1, 4, 5]);
1496-
1497-
//baz(arr[1 .. 3]); // cannot match length
14981497
}
14991498
-------------
15001499
)
15011500

1502-
$(P The following forms of slice expression can be convertible to a static array
1503-
type:)
1501+
$(P Certain other forms of slice expression can be implicitly converted to a static array
1502+
when the slice length can be known at compile-time.
1503+
1504+
$(SPEC_RUNNABLE_EXAMPLE_RUN
1505+
-------------
1506+
int[] da = [1, 2, 3];
1507+
int i = da[0]; // runtime variable
1508+
1509+
int[2] sa = da[i .. i + 2];
1510+
assert(sa == [2, 3]);
1511+
-------------
1512+
)
1513+
1514+
$(P The table below shows all the forms recognized:)
15041515

15051516
$(DL
15061517
$(DT $(D e)) $(DD An expression that contains no side effects.)
15071518
$(DT $(D a), $(D b)) $(DD Integers (that may be constant-folded).)
15081519
)
15091520

1510-
$(TABLE2 Computing array lengths during compilation,
1521+
$(TABLE2 ,
15111522
$(THEAD Form, The length calculated at compile time)
15121523
$(TROW $(D arr[]), The compile time length of $(D arr) if it's known.)
15131524
$(TROW $(D arr[a .. b]), $(D b - a))

0 commit comments

Comments
 (0)