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
}

}

Kof
  • 2,954
  • 6
  • 23
14w3u7
  • 11
  • 2
  • Have you seen this https://ethereum.stackexchange.com/questions/87451/solidity-error-struct-containing-a-nested-mapping-cannot-be-constructed – Kof May 03 '22 at 08:22

1 Answers1

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];
}

Kof
  • 2,954
  • 6
  • 23
  • 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 May 03 '22 at 07:21
  • Can you post the struct in question? – Kof May 03 '22 at 08:17
  • Also post the function that uses it and other related vars. – Kof May 03 '22 at 08:21
  • code https://rentry.co/87zrd – 14w3u7 May 03 '22 at 09:27
  • @14w3u7 updated my answer – Kof May 06 '22 at 06:07