Solidity Mapping – Assigning a Map as a Mapping’s Value in Solidity

contract-designcontract-developmentmappingsolidity

Essentially I have several mappings that I would love to be able to access with a string, or bytes32 value on occasion, but mostly access directly

mapping(int256 => mapping(int256 => address)) public mapOfA;
mapping(int256 => mapping(int256 => address)) public mapOfB;
mapping(int256 => mapping(int256 => address)) public mapOfC;

I want to be able to access one of these mappings depending on a variable (either string or bytes32)

I have tried:

mapping(string => mapping(int256 => mapping(int256 => address)) public mapIndex;

When I try to set:

mapIndex["A"] = mapOfA;

I get the following error:

Error: Mappings cannot be assigned to.
mapIndex["A"]

Am I missing something or is in not possible to assign a map as a mappings value?

Best Answer

You can do it, but ...

First, you need another ) for this to compile. Then you get:

mapping(string => mapping(int256 => mapping(int256 => address))) public mapIndex;

... and you need to drop public.

This is non-obvious, but you'll get "unimplemented feature" from the compiler because it's unable to contruct the "free" getter requested by the public modifier.

This compiles:

mapping(string => mapping(int256 => mapping(int256 => address))) mapIndex;

The task the compiler doesn't figure out for you is how to make a getter with three arguments to find its way to a specific element. You can

pragma solidity ^0.4.19;

contract Nested {

  mapping(string => mapping(int256 => mapping(int256 => address))) mapIndex;

  function getMapIndex(string a, int256 b, int256 c) public view returns(address d) {
      return mapIndex[a][b][c];
  }    

  function setMapIndex(string a, int256 b, int256 c, address d) public returns(bool success) {
      mapIndex[a][b][c] = d;
      return true;
  }
}

Hope it helps.

Related Topic