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

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

1 Answer 1


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){

    function removeSingleUser(string _key){

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.


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.