Return a struct in Solidity
Private and internal can be returned as is
For functions with private or internal modifiers, you can return the struct without being particularly careful.
struct UserInfo {
...
}
mapping(uint256 => UserInfo) internal _userIdToUserInfo;
function getUserInfo(uint256 _userId) internal view returns (UserInfo memory) {
return _userIdToUserInfo[_userId];
}
Caution:
Code for solidity 0.5.4.
For 0.4.x, do not specify a storage area in the value to return.
returns (UserInfo memory)
-> returns (UserInfo)
externa and public specify ABIEncoderV2
When returning a struct outside of solidity, ABIEncoderV2 must be specified.
pragma experimental ABIEncoderV2;
By doing this, the struct can be returned to the outside, and it can be referenced from web3 as well.
Warning using ABIEncoderV2
By specifying ABIEncoderV2, the following warning "Don't use it in live deployment" will be issued.
Experimental features are turned on. Do not use experimental features on live deployments.
What does this attention refer to?
Currently, when returning a struct in a solidity function, it is necessary to specify ABIEncoderV2, but if you specify this, the compiler will warn you not to use it in live deployments. However, this is not a security issue, but it seems to be a note that the amount of gas used will be large. https://t.co/eB7VknHaHL
— Ryo Komiyama (@ryoheikomy) Feb. 18, 2019
I wrote it on twitter, so I will quote it, but it is not a warning against security, but a warning against the increase in gas usage. Therefore, it is not necessary to be "Since it can not be used in the production environment, the struct has to return for each element in the end", it seems good to think that "it seems to take gas, so let's decide whether to use it after trying how long it will take".
Summary
When returning a struct in Solidity, specify ABIEncoderV2 as follows:
pragma experimental ABIEncoderV2;

Ryo Komiyama
🏔Kyuzan (http://kyuzan.com)🏔 UI・UXにフォーカスしたブロックチェーンプロダクトを作ります / エグリプト (http://eggrypto.com) をリリースしました / 全ての新しい技術に興味があります / ▼ex Rhizomatiks Research ▼ex 東大 暦本研
Updated on February 18, 2019