On 10/04/2012 07:09 AM, Jesse Phillips wrote:
On Thursday, 4 October 2012 at 13:55:39 UTC, Jacob Carlborg wrote:
void foo (inout int[] arr)
{
auto a = { auto b = arr[0]; };
}
void main ()
{
auto a = [3, 4, 5];
foo(a);
}
Compiling the above code with DMD 2.060 results in the following error
message:
Error: variable main.foo.__lambda1.b inout variables can only be
declared inside inout functions
Failed: /Users/jacob/.dvm/bin/dvm-current-dc -v -o-
'/Users/jacob/development/d/main.d' -I'/Users/jacob/development/d'
>/Users/jacob/development/d/main.d.deps
Is this a bug, a limitation of inout/delegate or am I doing something
else wrong?
IIRC, inout must be applied to the return type too, and it only works in
templates.
inout is like a template on 'mutable', const, and immutable; but it need
not be applied to templates. Here is a simple example that transfers the
mutability to the return type:
http://ddili.org/ders/d.en/function_parameters.html
inout(int)[] trimmed(inout(int)[] slice)
{
if (slice.length) {
--slice.length; // trim from the end
if (slice.length) {
slice = slice[1 .. $]; // trim from the beginning
}
}
return slice;
}
All three blocks below compile:
{
int[] numbers = [ 5, 6, 7, 8, 9 ];
// The return type is slice of mutable elements
int[] middle = trimmed(numbers);
middle[] *= 10;
writeln(middle);
}
{
immutable int[] numbers = [ 10, 11, 12 ];
// The return type is slice of immutable elements
immutable int[] middle = trimmed(numbers);
writeln(middle);
}
{
const int[] numbers = [ 13, 14, 15, 16 ];
// The return type is slice of const elements
const int[] middle = trimmed(numbers);
writeln(middle);
}
inout can also be applied to member functions where the 'this' reference
takes the mutability of a parameter and all of the member accesses
becomes mutable, const, or immutable.
Ali