1

I'm aware of this post:

Accessing a mapping within a struct via Truffle console

However, it seems to me, it does not provide a clear answer. Also, my question is more generic and not just for truffle. Also, there's similar code in here (section "structs") but couldn't find any answer to the below questions.


Case 1:

Assume we have the following pseudo-code in solidity:

mapping (uint => BB) public map_1; 

struct BB{

  mapping (uint => address) map_2;
}

Question : Given a key, how can I access the content of map_2 in Geth or a user interface?


Case 2:

Assume we have the following pseudo-code in solidity:

mapping (uint => BB) public map_1; 

struct AA{
uint val;
}

struct BB{

  mapping (uint => AA) map_2;
}

My question for this case remains the same as the one for case 1.

2 Answers 2

2

You can access the case 1s mapping by given the both keys. The key for map_1 and key for map_2. Use pragma solidity ^0.4.20; when compiling

Case 1

contract test {
    struct BB {
        mapping(uint => string) map_2;
    }
    mapping(uint => BB) map_1;

    function test() public {
        map_1[1].map_2[1] = "hello"; //setting temp value
    }

    function maping() public view returns(string) {
        return map_1[1].map_2[1]; //accessing the value
    }
}

Case 2

contract test {
    struct BB {
        mapping(uint => AA) map_2;
    }
    struct AA{
        uint val;
    }
    mapping(uint => BB) map_1;

    function test() public {
        map_1[1].map_2[1].val = 10;
    }

    function maping() public view returns(uint) {
        return map_1[1].map_2[1].val;
    }
}
0
2

Case 1

You cannot make map_1 public because the compiler doesn't know how to construct the "free" getter than comes with public. You have to make it yourself, like this:

pragma solidity 0.5.1;

contract Case1 {

    struct BB{
        mapping (uint => address) map_2;
    }

    mapping (uint => BB) map_1; 

    function getter(uint structId, uint mapId) public view returns(address) {
        return map_1[structId].map_2[mapId];
    }  
}

That means you have a function that accepts two uint arguments and returns an address at the requested coordinates.

Case 2

Same as above.

contract Case2 {

    struct AA{
        uint val;
    }

    struct BB{

        mapping (uint => AA) map_2;
    }

    mapping (uint => BB) map_1; 

    function getter(uint BBId, uint AAId) public view returns(uint val) {
        return map_1[BBId].map_2[AAId].val;
    }
}

In this case val in the returns phrase is merely an optional label for the uint that will be returned.

Hope it helps.

1
  • Thanks a lot for the answer Rob!
    – Aydin
    Commented Jun 20, 2019 at 9:24

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.