1

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 
        }

1 Answer 1

2

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.

3
  • Wow, that's amazing! Thank you, this is exactly what I'm looking for, but how do I Initialize struct inside a struct? Oct 16, 2018 at 22:19
  • Thanks for accepting that answer. We mustn't anger the mods. If you post that as a new question I'll probably take a stab at it. ;-) Oct 17, 2018 at 1:04
  • ok I did that -> ethereum.stackexchange.com/questions/60728/… Oct 17, 2018 at 13:25

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.