Strangely, Solidity allows functions to return multiple values. You might not be used to this if you've got some programming experience. But this feature could turn out to be super useful. Here is a snippet from the solidity docs to demonstrate this:
contract sample {
function a() returns (uint a, string c){
// wrap all returned
// values in a tuple
return (1, "ss");
}
function b(){
uint A;
string memory B;
//A is 1 and B is "ss"
(A, B) = a();
//A is 1
(A,) = a();
//B is "ss"
(, B) = a();
}
}
The function a()
in the code returns multiple values and to achieve that simply wrap all the values you want to return in a tuple "()".
So a()
would return both 1 and the string "ss". Also remember to declare their types in the returns
part of the function declaration.
Extract both values from a()
So how do we extract those values?
Well, that's what the function b()
does. When you call a()
, you can assign the result to a tuple with variables equals to the number of values you want to extract.
function b(){
//...
(A, B) = a();
}
This will assign 1 to A and "ss" to B. What if you need just a single value, perhaps just the first value returned by a()
?
Extract a single value from a()
To extract a single value, do something like this...
function b(){
// not all elements have to be
// specified (but the number must match).
(,B) = a();
}
That should assign the second return value, "ss" to B. Observe how we left the first value in the tuple empty, we kinda have to do that to extract B. Same goes for extracting the first value
function b(){
// not all elements have to be
// specified (but the number must match).
(A,) = a();
}
Wrapping Up
And that's how to write functions that return multiple values and use those values in your code. I hope this has been helpful. Thanks for reading this quick snappy content. I can't wait to see you what do with this knowledge. I'm rooting for you.
koha
Top comments (0)