Add Element to list not Working

Chris Pons cmpons at gmail.com
Mon Apr 2 11:27:18 PDT 2012


Ah, thank you. I didn't realize taht SList is a struct and that 
it used value semantics. That clears this up.

On Monday, 2 April 2012 at 14:22:25 UTC, Ali Çehreli wrote:
> On 04/01/2012 11:18 PM, Chris Pons wrote:
> > Thanks. I tried doing this and the list didn't update:
> >
> > void AddToList( SList!int list, int i )
> > {
> > list.insert( i );
> > }
>
> Oh, that has nothing to do with SList. SList is a struct and as 
> a fundamental rule of D, structs are copied to functions. SList 
> happens to be a struct. The list parameter of AddToList and the 
> list variable that is passed to the function as an argument are 
> two different variables.
>
> >
> > SList!int intList;
> >
> > AddToList( intList, 42 );
> >
> > but when I switched to this, it worked:
> >
> > SList!int intList;
> >
> > void AddToList( int i )
> > {
> > intList.insert( i );
> > }
>
> Global variables are not a good solution of course. :(
>
> The solution here is to pass the argument by-reference by the 
> 'ref' keyword:
>
> void AddToList( ref SList!int list, int i )
> {
>     // ...
> }
>
> Ali
>
> P.S. There is this chapter that covers 'ref' and most (but not 
> all) types of function parameters:
>
>   http://ddili.org/ders/d.en/function_parameters.html




More information about the Digitalmars-d-learn mailing list