A matter of inout
Artur Skawina
art.08.09 at gmail.com
Fri Jul 27 10:26:45 PDT 2012
On 07/27/12 19:06, bearophile wrote:
> Artur Skawina:
>
>> 'inout' basically means 'local const' - if you'd allow inout
>> data to be modified then it wouldn't be possible to call the
>> function with a const or immutable argument - which is the
>> whole point of inout...
>> You probably want 'inout(T)[]' if you're going to alter the
>> array.
>
> Using inout(T)[] gives the same error:
>
> import std.stdio;
> inout(T)[] forwardDifference(T)(inout(T)[] s, in int n) pure {
> foreach (_; 0 .. n)
> s[] -= s[1 .. $];
> return s[0 .. $ - n];
> }
> void main() {
> immutable A = [90.5, 47, 58, 29, 22, 32, 55, 5, 55, 73.5];
> foreach (level; 0 .. A.length)
> writeln(forwardDifference(A.dup, level));
> }
This alters not only the array, but also modifies the elements.
Using just 'T' instead of 'inout(T)' will do the right thing;
why would you like to use inout in cases like this one? 'inout'
allows you to not write two or more /identical/ function bodies
when the code can deal with immutable/const/mutable; functions
that modify the data in-place obviously can't do that.
artur
More information about the Digitalmars-d-learn
mailing list