On Mon, 11 Feb 2013 17:13:21 -0000, Dicebot <m.stras...@gmail.com> wrote:

On Monday, 11 February 2013 at 16:54:04 UTC, Jonathan M Davis wrote:
The const(T)[] cannot alter the original array at all, so I concur with Steven in that the complaints about not wanting to use tail-const make no sense.
Maybe this article will help clear things up:

And I exactly want to prohibit altering original array. What I want is to copy slice (without deep copying of data) and alter this fresh copy. I can't see how it contradicts immutability guarantees or D array design.

This *does* prohibit altering the original array ("test" passed by main below) without deep copying the data, and allows you to alter the fresh copy ("arr" inside the function).

Example:

import std.stdio;

void foo(const(string)[] arr)
{
  // arr[0] = "aa";  // Error: arr[0] isn't mutable
  arr.length = 10;
  writefln("foo arr.length = %d", arr.length);
}

void main()
{
  const(string[]) test = ["a", "b"];

  // test[0] = "aa";   // Error: test[0] isn't mutable
  // test.length = 10; // Error: variable ****.test cannot modify const
  foo(test);
  writefln("test.length = %d", test.length);
}

What you have to realise is that when you pass an array/slice in D, you get a copy of that array/slice in the function. Just like when you pass an 'int' or any other "value" type.

Think of the array/slice as this struct:

struct array
{
  int length;
  void *ptr;
}

Passing that to a function would copy the entire struct into the function parameter, altering that parameter would not alter the original. array/slices are the same.

The data referred to by 'ptr' is not copied, and neither are the elements of an array/slice.

If you did want to alter the original, you'd pass the array/slice by 'ref'erence.

R

--
Using Opera's revolutionary email client: http://www.opera.com/mail/

Reply via email to