Multiple return value as requirements for safety and performance

Ilya Yaroshenko via Digitalmars-d digitalmars-d at puremagic.com
Tue Dec 20 06:56:37 PST 2016


On Tuesday, 20 December 2016 at 14:47:28 UTC, Walter Bright wrote:
> On 12/20/2016 5:47 AM, Ilya Yaroshenko wrote:
>> One good thing for safety and CTFE is allow multiple return 
>> value. In
>> combination with `auto ref` it is _very_ powerful:
>>
>> ----
>> auto ref front()
>> {
>>   // Returns 2 values, each value is returned by reference if 
>> possible
>>   return (a.front, b.front);
>> }
>> ----
>
> http://dlang.org/phobos/std_typecons.html#.tuple
>
> auto ref front() {
>     return tuple(a.front, b.front);
> }

Tuples can not work with auto ref. This is a reason for this 
thread.
Proof:
-----
import std.typecons: tuple;

int[] a = [1,2,3];
int[] b = [1,2,3];

auto ref front() {
	import std.range: front;
     return tuple(a.front, b.front);
}

void main()
{
	front()[0] = 1000;
	import std.stdio;
	writeln(front()[0]);
}
-----
Output: 1
-----

As you can see the output should be 1000, but it is 1.

It can be solved with pointers, and Mir will have their own 
tuples which use pointers. But it is not good because:
1. Pointers are not CTFE-able.
2. Pointers are not safe.



More information about the Digitalmars-d mailing list