In this article, we will discuss the public function with I/O restrictions and returning multiple outputs in Solidity.
Input:
Invalid inputs for a public function in Solidity:
- Map, eg: mapping(uint256 => address).
- Multi-dimensional and unfixed size arrays, eg: uint[][]. This is only true for the version below 0.7. The new version 0.8 of Solidity is supported for multi-dimensional and unfixed size arrays for the input of the public function.
Example:
pragma solidity ^0.8.0;contract FunctionExample {
function mapFunction(mapping(uint256 => address) memory input) public {
}
}
When you try to compile the above smart contract, you will get a compile error:
TypeError: Types containing (nested) mappings can only be parameters or return variables of internal or library functions.
A similar example for multi-dimensional and unfixed size arrays (Solidity below 0.7):
pragma solidity ^0.7.0;contract FunctionExample {
function arrayFunction(uint[][] memory input) public {}
}
Error:
TypeError: This type is only supported in ABI coder v2. Use "pragma abicoder v2;" to enable the feature.
To fix that, you can change to use Solidity ^0.8.0 or use a multi-dimensional array with fixed size:
1/
pragma solidity ^0.8.0;contract FunctionExample {
function arrayFunction(uint[][] memory input) public {}
}
2/
pragma solidity ^0.7.0;contract FunctionExample {
function arrayFunction(uint[3][3] memory input) public {}
}
The reason for this restriction: Gas. A bigger array will need more used gas. With a map or unfixed size array, the gas can be infinity. We also cannot predict the amount of will be used of gas. The smart contract should be: simple, reliable, and predictable.
Output:
Invalid output for a public function in Solidity (same as Input rule):
- Map, eg: mapping(uint256 => address).
- Multi-dimensional and unfixed size arrays, eg: unit[][]. ]. This is only true for the version below 0.7.
Example with compile error:
pragma solidity ^0.7.0;contract FunctionExample {
mapping(uint256 => address) mapData;
uint[][] unfixedSizeArray;
function getMapdata() public returns(mapping(uint256 => address) memory){
return mapData;
}
function getArrayData() public returns ( uint[][] memory ) {
return unfixedSizeArray;
}
}
Restructuring assignments:
pragma solidity ^0.8.0;contract FunctionExample {
function returnMultipleValues() public view returns ( uint, bool, address) {
return (12 , true , msg.sender);
}function getData() public view returns ( uint, bool, address, string memory){
(uint a, bool b, address c ) = returnMultipleValues();
return (a, b, c, "Hello World");
}
}