Add Element to list not Working

Ali Çehreli acehreli at yahoo.com
Mon Apr 2 07:22:24 PDT 2012


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