Using a tuple as a function parameter

Paul Backus snarwin at gmail.com
Fri Nov 22 18:03:46 UTC 2024


On Friday, 22 November 2024 at 16:36:43 UTC, Andrew wrote:
> I'm getting started using D for some small personal projects 
> and one thing I wanted to do was use a helper function for a 
> tuple. I declared the function like this:
>
>     string getOrZeroth(Tuple!(string, string, string) tup, int 
> i) pure {
>         return tup[i] == "" ? tup[0] : tup[i];
>     }
>
> and would like to use it like this:
>
>     auto foo = tuple("a", "", "c");
>     writeln(foo.getOrZeroth(1)); // prints a
>
> but when I try it, I'm getting the below error:
>
>> Error: variable \`i\` cannot be read at compile time

You can do this with a `switch` statement:

     string getOrZeroth(Tuple!(string, string, string) tup, int i)
     {
         switch (i)
         {
             static foreach (j; 0 .. tup.length)
             {
                 case j:
                     return tup[j] == "" ? tup[0] : tup[j];
             }
             default:
                 assert(0, "Tuple index out of bounds");
         }
     }


More information about the Digitalmars-d-learn mailing list