Can match arms return more than one value?


#1

I have two (or possibly more) functions that execute different code under unique conditions but return two values with the same type.

The different conditions are set with a flag but there is a limitation that I should not change the original function therefore this enhancement is a wrapper function with a switch of sorts, and this also allows for future enhancements.

In the wrapper function I wanted the match statement to return the two values dependent on the flag, but this causes an error at compile time because match does not appear to allow two variables to be returned from a function that is associated with the arm.

fn reward1(factor: u64, mut standard_reward: u64, number:u64) -> (u64, u64){
	/* do some processing*/
	(policy, reward)
}

fn reward2(factor: u64, mut standard_reward: u64, number:u64) -> (u64, u64){
	/* do some other processing*/
	(policy, reward)
}

fn select_policy(factor: u64, mut standard_reward: u64, flag:u64, number:u64) -> (u64, u64){
	let policy:u64;
	let reward:u64;
	match flag {
		0 => (policy, reward) = reward1(factor, standard_reward, number),
		1 => (policy, reward) = reward2(factor, standard_reward, number),
		_ => reward = standard_reward,
	}
	(policy, reward)
};

is there a way to achieve this?


#2

Yes. Simply return a tuple:

let (policy, reward) = match flag {
	0 => reward1(factor, standard_reward, number),
	1 => reward2(factor, standard_reward, number),
	_ => (standard_reward, 0u64),
};
(policy, reward)

Also, your code looks very complicated to me :slight_smile: I’d do that much simpler.


#3

Or, even better:

fn select_policy(factor: u64, mut standard_reward: u64, flag:u64, number:u64) -> (u64, u64){
	match flag {
		0 => reward1(factor, standard_reward, number),
		1 => reward2(factor, standard_reward, number),
		_ => (standard_reward, 0),
	}
};

match is itself an expression, so no need to assign and then just return the tuple.


#4

Yes, I know, that is why I have told “Your code looks overcompilcated to me”. :slight_smile:


#5

OK so the select_policy function returns whatever the match arm provided without having to explicitly state what is returned. This answer works for me.


#6

That’s kind of a tease without explanation.


#7

Haha. No, I would post my simplier soultion but I don’t know the OP’s intentions, probably, this is just an example code an he only needs to know how to return a tuple from a match, nothing more. So I decided just to answer his question and give him a hint that it is possible to do easier, - if he was interested in that he would ask then :slight_smile: