Calls to struct methods and immutable

Ali Çehreli acehreli at yahoo.com
Thu Nov 15 09:40:43 PST 2012


On 11/15/2012 06:24 AM, Joseph Rushton Wakeling wrote:

 > The practical situation I'm dealing with is that the a struct gets built
 > inside a function, based on data read from files. Once the data has been
 > written to the struct, it should never be changed again.

If you don't want the callers be able to change, then return 
immutable(Foo). Otherwise, if the caller wants to use the object as 
immutable, then the user should declare immutable:

a) Don't allow users to modify:

immutable(Foo) makeFoo()
{
     Foo foo;
     foreach (i; 0..10)
         foo.add( /* new data point */ );
     return foo;
}

b) The user wants to play safe:

auto makeFoo()
{
     Foo foo;
     foreach (i; 0..10)
         foo.add( /* new data point */ );
     return foo;
}

void main()
{
     immutable foo = makeFoo();
}

Both of those compile with dmd 2.060.

 > I'm deluging the list with a
 > bunch of questions

Please continue to do so. That is what this forum is for. Your questions 
help us all. :)

Ali



More information about the Digitalmars-d-learn mailing list