Returning multiple arrays from function - struct or byref the only option?

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Oct 18 07:56:05 PDT 2014


On Wednesday, 15 October 2014 at 17:56:06 UTC, Ali Çehreli wrote:
> - Unlike a struct, the members are anonymous. (Yes, tuples 
> members can have names as well but not when returning or 
> creating conveniently by 'return tuple(a, b)'.)

This works, but I agree it is a bit obscure (you may want to add 
it to your book if it's not already there):

import std.typecons;

Tuple!(int[], "left", int[], "right") foo(int n, int m)
{
	return typeof(return)(new int[](n), new int[](m));
}

void main()
{
	auto res = foo(2, 3);
	assert(res.left.length == 2);
	assert(res.right.length == 3);
}


The problem is that D does not allow implicit conversions when 
returning results from a function. Tuple!(int[], int[]) is 
implicitly castable to Tuple!(int[], "left", int[], "right"), but 
you cannot return the result of tuple(new int[](n), new int[](m)) 
from foo(), as they are technically still different types, which 
would require an implicit conversion. This is (IMO) a problem; 
it's extremely annoying when trying to use std.typecons.Algebraic.



More information about the Digitalmars-d-learn mailing list