I am using Solc version 0.7.0 installed by npm. When I try to create a Struct that contains mapping, I received an error: "Struct containing a (nested) mapping cannot be constructed."
Please check the code:
// SPDX-License-Identifier: MIT
pragma solidity 0.7.0;
contract Test {
struct Request {
uint256 value;
mapping(address => bool) approvals;
}
Request[] public requests;
...
function createRequest(
uint256 value
) public {
Request memory newRequest = Request({// here the compiler complains
value: value
});
requests.push(newRequest);
}
}
When I use older versions of solc, the code compiles without problems.
Thank you in advance!
Struct can also contain array and mapping (including an array of its own struct type).
Indeed, since version 0.7. 0, structs or arrays that contain a mapping can only be used in storage, so Solidity complains because variables in an instantiation function would be in memory by default.
Mapping in Solidity acts like a hash table or dictionary in any other language. These are used to store the data in the form of key-value pairs, a key can be any of the built-in data types but reference types are not allowed while the value can be of any type.
This should work:
function createRequest(uint256 value) public {
Request storage newRequest = requests.push();
newRequest.value = value;
}
Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With