Shall I use immutable or const while passing parameters to functions
John Colvin via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Apr 7 08:24:57 PDT 2015
On Tuesday, 7 April 2015 at 15:11:39 UTC, tcak wrote:
> I have data in memory, and I want a function to take a part of
> data for processing only. It will only read and won't change.
>
> char[] importantData;
>
>
> With Immutable,
>
> void dataProcessor( string giveMeAllYourData ){}
>
> dataProcessor( cast( immutable )( importantData[5 .. 14] ) );
>
>
>
> With Const,
>
> void dataProcessor( in char[] giveMeAllYourData ){}
>
> dataProcessor( cast( const )( importantData[5 .. 14] ) );
>
>
> (Code with const wasn't tested)
>
> Which one is better? I didn't understand it very well in
> http://dlang.org/const3.html this page.
const means "I will not modify this via this variable" and
immutable means "no one will modify this from anywhere"
Don't cast to immutable unless you are sure what you are doing.
Immutable is a strong guarantee, it's easy to break it by
accident if you're casting things. The safest way of getting an
immutable array is with the .idup property.
You don't have to cast to const most of the time. mutable is
implicitly convertible to const:
void foo(const int[] a){}
void main()
{
int[] a = [1,2,3,4];
foo(a);
foo(a[0..2]);
}
Also, see https://archive.org/details/dconf2013-day01-talk02
In general, immutable in an API allows greater freedom for the
implementation, const allows for greater freedom/convenience for
the API user. Which is more important depends on your exact
problem.
More information about the Digitalmars-d-learn
mailing list