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

2

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!

Happy answered 30/7, 2020 at 9:38 Comment(1)
You can refer to this ethereum.stackexchange.com/a/97883/68718 for better clarityDentelle
C
14

This should work:

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

Cheers!

Checklist answered 7/2, 2021 at 5:22 Comment(0)
L
9

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;
}
Looksee answered 2/4, 2021 at 7:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.