Returning multiple values from a function

Azi Hassan via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Sep 4 04:04:05 PDT 2017


On Monday, 4 September 2017 at 09:22:25 UTC, Vino.B wrote:
> Output :
> 1
> 2
> ["C:\\Temp\\TEAM1\\BACKUP", "C:\\Temp\\TEAM2\\ARCHIVE"]
>
> Required Output:
> Test1 = 1
> Test2 = 2
> Path = ["C:\\Temp\\TEAM1\\BACKUP", "C:\\Temp\\TEAM2\\ARCHIVE"]
>
> From,
> Vino.B

If you just need it to be displayed then you can add it to the 
writeln call : writeln("Test 1 = ", Params[0]);

But if you want to do it dynamically then maybe you should be 
using an associative array or a tuple of tuples :

import std.stdio;
import std.array;
import std.typecons;

alias Result = Tuple!(
	Tuple!(string, int),
	Tuple!(string, int),
	Tuple!(string, string[])
);

Result Params () {
	int Test1;
	int Test2;
	string[] File1;
	string[] File2;
	auto Path = appender!(string[]); //string[] path; 
path.reserve(2) ?
	Test1 = 1;
	Test2 = 2;
	File1 = ["C:\\Temp\\TEAM1\\BACKUP"];
	File2 = ["C:\\Temp\\TEAM2\\ARCHIVE"];
	Path ~= File1;
	Path ~= File2;
	return tuple(
		tuple("Test1", Test1),
		tuple("Test2", Test2),
		tuple("Path", Path.data)
	);

}

void main (){
	auto res = Params();
	writeln(res[0][0], " = ", res[0][1]);
	writeln(res[1][0], " = ", res[1][1]);
	writeln(res[2][0], " = ", res[2][1]);
}

You can also loop through res :

void main (){
	auto res = Params();
	foreach(r; res)
		writeln(r[0], " = ", r[1]);
}


More information about the Digitalmars-d-learn mailing list