[Ethereum] How to create a mapping of string and struct array in solidity

go-ethereumremixsolidity

I am new to solidity trying to learn it.

I want to create a mapping like

mapping (string=>User[]) public  companyUserMap;

Where User is a struct

struct User {
   string userId;
   uint roleId;
}

Struggling with writing a function for adding / removing/ iterating a user to the mapping.

function addUser() {
    User usr= User("user01",1); 
    User usr2= User("user02",2);
    User usr[]={usr,usr2};
    //add the users created above to the mapping
    companyUserMap.push("c1",usr[])
}

TypeError: Type struct AuthorizationManager.User memory is not implicitly convertible to expected type struct AuthorizationManager.User storage pointer.

Can someone please help me with functions for adding / removing / iterating the users and the mapping

Best Answer

These are the basic patterns you need and you can base your more sophisticated getter/setter/remover functions on.

pragma solidity ^0.4.11;

contract AuthorizationManager{
    struct User{
      string userId;
      uint roleId;
    }

    mapping (string => User[]) companyUserMap;

    function addUser(string _key,string _userId, uint _roleId){
        companyUserMap[_key].push(User(_userId,_roleId));
    }

    function removeSingleUser(string _key){
        companyUserMap[_key].length--;
    }
}

Generally you should be really cautious when you iterate over large mappings, arrays etc. You could easily run out of gas and potentially lock your contract up. This is an instructive example.

Related Topic