Solidity Named Returns
Named returns are return values that carry names inside the returns part of a function. A function sets those names in its body, and the caller receives all of them at once.
A function can return two values
pair returns the number sent in and the next number after it. The caller unpacks the two values into two separate variables.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract PairMaker {
function pair(uint256 number) public returns (uint256, uint256) {
return (number, number + 1);
}
}
Named returns are set by name
split names its returns half and rest. The body sets each name, and there is no return statement at all.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Splitter {
function split(uint256 total) public returns (uint256 half, uint256 rest) {
half = total / 2;
rest = total - half;
}
}
Each named return is set one by one
doubleAndTriple sets doubled first and tripled second. The caller unpacks both results and can check each one on its own.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract DoubleTriple {
function doubleAndTriple(uint256 number) public returns (uint256 doubled, uint256 tripled) {
doubled = number * 2;
tripled = number * 3;
}
}
Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract BoxMeasure {
uint256 public lastArea;
function measure(uint256 width, uint256 height) public returns (uint256 area, uint256 perimeter) {
area = width * height;
perimeter = 2 * (width + height);
lastArea = area;
}
}
Key points
- Multiple returns: the returns part can list two or more types.
- Named return: each returned value can carry its own name.
- Set by name: assign to a named return inside the body to set that result.
- Ending: when the body ends, the named values go back to the caller.
- Unpack: the caller writes (uint256 a, uint256 b) = a call to receive both values.
- Order: the values come back in the order the returns part lists them.
In this example, measure names its two returns area and perimeter and sets each one by name in the body. The caller unpacks both values from one call. The function also stores the area it just named, so lastArea can be read afterwards.
Note
a named return needs no return statement, because the names already hold the results.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
How does the body of a function set a named return called total?