Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solidity, Solc Error: Struct containing a (nested) mapping cannot be constructed

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!

like image 755
coding Avatar asked Jul 30 '20 09:07

coding


People also ask

Can a struct contain a mapping solidity?

Struct can also contain array and mapping (including an array of its own struct type).

Can a struct contain a mapping?

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.

What is mapping in solidity?

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.


1 Answers

This should work:

function createRequest(uint256 value) public {
    Request storage newRequest = requests.push();
    newRequest.value = value;
}

Cheers!

like image 154
user1506104 Avatar answered Sep 22 '22 05:09

user1506104