I got quite an interesting question. I have created an array of structs, and in each struct, I have an array of address. Then I got a method that when its called on given struct [index] its adds sender address to an array of an address of given struct.

Now my question is, is it possible to also add a string to each element of address array? From what I understand you can’t have 2d array of 2 different types?

 struct Project{
            int id;
            string name;
             int votes;    
           address[] voters;

        }
    Project[] public projects;

    function vote(uint index , string comment) public {
           Project storage project = projects[index];
        Project.votes++       
           project.voters.push(msg.sender);
    // now to add a string (comment) to each address that is added to address array 
        }
up vote 0 down vote accepted

I had to fiddle around to correct some minor issues, then came up with this:

contract FunWithArrays {

  struct Project{
    int id;
    string name;
    int votes;    
    address[] voters;
    string[] comments;
  }

  Project[] public projects;

  function vote(uint index , string comment) public {
    Project storage project = projects[index];
    project.votes++;     
    project.voters.push(msg.sender);
    project.comments.push(comment); 
  }
}

It's not the only way. You can't have a 2D array with multiple types. You can form such things with structs and you can even have an array of structs. So, a variant would look like this:

contract FunWithArrays {

  struct Voter {
      address voter;
      string comment;
  }

  struct Project{
    int id;
    string name;
    int votes;    
    Voter[] voters;
  }

  Project[] public projects;

  function vote(uint index , string comment) public {
    Project storage project = projects[index];
    project.votes++;     
    Voter memory v;
    v.voter = msg.sender;
    v.comment = comment;
    project.voters.push(v);
  }
}

Whenever you work with such structures you'll inevitably encounter some organizational issues. Be sure to check out some common patterns: Are there well-solved and simple storage patterns for Solidity?

Hope it helps.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.