4

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

1 Answer 1

3

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.

0

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.