0

While writing a contract that uses structs, I'm getting an error by the linter "Struct containing a (nested) mapping cannot be constructed".

According to this, the problem with structs is you cannot nest maps. In the design I'm using there's a map of uint8 => struct.

Should I switch to contracts or build a db scheme in the main contract?

Here's a sample code -

struct Room {
    uint16 id;
}
struct Apartment {
    uint8 id;
    mapping(uint8 => Room) roomMap;
}
struct Building {
    uint8 id;
    mapping(uint8 => Apartment) apartmentMap; //error here
}

contract Network {
    constructor() {}

    uint8 count = 0;
    mapping(uint8 => Building) public buildingMap;

    function appendBuilding(uint8 id) public {
        Building storage building;
        building.id = id;
        buildingMap[id] = building; //error here
    }
}
1

1 Answer 1

0

Update

After looking at the OP's code, it seems like a incorrect use of mapping and struct.

Instead of this implementation -

    function appendBuilding(uint8 id) public {
        Building storage building;
        building.id = id;
        buildingMap[id] = building; //error here
    }

it should be coded like that -

    function appendBuilding(uint8 id) public {
        buildingMap[id].id = id;
    }

Using multiple contracts for data storage is not a good idea.

You can nest maps with struct at the end in the following way -

    struct MyStruct {
        uint value1;
        uint value2;
        mapping(address => uint) map;
    }

    mapping(address => mapping(address => MyStruct)) public data;

    constructor() {
    }

    function write(address addr1, address addr2, address addr3, uint value) public {
        data[addr1][addr2].map[addr3] = value;
    }

    function read(address addr1, address addr2, address addr3) public view returns (uint) {
        return data[addr1][addr2].map[addr3];
    }
5
  • To be more precise, I get the following error: Struct containing a (nested) mapping cannot be constructed. I have struct maps nesting struct maps which is not allowed, and the issue I'm conflicted about is how to resolve it effectively. As per the question, smart contracts vs db
    – 14w3u7
    Commented May 3, 2022 at 7:21
  • Can you post the struct in question?
    – Kof
    Commented May 3, 2022 at 8:17
  • Also post the function that uses it and other related vars.
    – Kof
    Commented May 3, 2022 at 8:21
  • code rentry.co/87zrd
    – 14w3u7
    Commented May 3, 2022 at 9:27
  • @14w3u7 updated my answer
    – Kof
    Commented May 6, 2022 at 6:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.