I was reading some functions of UniswapV2Router and I face the following code:
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
The function return uint[] memory amounts
but actually there is no return in the body. Can you explain me what I miss?
I was expecting to see this variable declared somewhere but I still didn't see it anywhere.
returns (uint[] memory amounts)
This snippet declares the amounts
variable and states that the amounts
variable should be returned at the end of the function.
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
And this line assigns a value to amounts
.
It's simply a shorthand syntax for returning specific variables at the end of the function without having to explicitly write the return
statement.
Another example:
function foo() external pure returns (uint256 number) {
number = 100;
// TODO rest of your function
}
returns the same value as
function foo() external pure returns (uint256) {
uint256 number = 100;
// TODO rest of your function
return number;
}
From the docs page:
The names of return variables can be omitted. Return variables can be used as any other local variable and they are initialized with their default value and have that value until they are (re-)assigned.
You can either explicitly assign to return variables and then leave the function as above, or you can provide return values (either a single or multiple ones) directly with the
return
statement: