0
library Test{

  struct Data {
    mapping (bytes => string) a;
  }

  function inc(Data storage self) internal {
     self.a[0] = 'ban';
     self.a[1] = 'sam';
 }
}

contract Example{

  address recipient = 0x0000cafebabe;

  function getNames() view{
    Test.Data.a[0];
  }
}

I'm facing issue while calling getNames

1
  • Please share more info on what you exactly want to achieve and what the error is. Your current code is very confusing, making it hard for us to guess your goals.
    – phaze
    Jun 9, 2022 at 11:04

1 Answer 1

1

You can instantiate the mapping (defined in your Test library) into your smart contract and then you can handle all data inside it. Below you can see an example how to do this:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

library Test{

    struct Data {
        mapping (bytes => string) a;
    }

    function inc(Data storage self) internal {
        self.a['0'] = "ban";
        self.a['1'] = "sam";
    }

}

contract Example{

    address recipient = 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4;
    // NOTE: Declare a new instance about mapping inside Data struct in 'Test' library
    Test.Data Datastruct;

    // NOTE: Function that allow you to call 'inc' function inside 'Test' Library for fill the mapping
    function setName() public {
        Test.inc(Datastruct);
    }

    function getNames() external view returns(string memory) {
        // NOTE: With instance about mapping, you can read data 
        return Datastruct.a['0'];
    }

}

I put NOTES for make you understand the different steps that I made.

1
  • Thanks, @kerry99, for helping it out, with such a nice explanation. Jun 14, 2022 at 7:32

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.