17

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!

coding
  • 627
  • 7
  • 20
  • 1
    You can refer to this https://ethereum.stackexchange.com/a/97883/68718 for better clarity – Ayan Apr 27 '21 at 09:46

2 Answers2

13

This should work:

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

Cheers!

user1506104
  • 6,554
  • 4
  • 71
  • 89
8

This worked in my case:

struct Request{
    uint256 value;
    mapping(address => bool) approvals;
}
            
uint256 numRequests;
mapping (uint256 => Request) requests;
        
function createRequest (uint256 value) public{
    Request storage r = requests[numRequests++];
    r.value= value;
}
Debjit Datta
  • 111
  • 1
  • 6