My problem
Suppose I have this struct:
struct TextThatWorks {
bytes32 text;
uint reads;
}
How can I add a address
variable to it?
What I tried
I tried simply adding address someadress;
inside the struct declaration, like so:
struct TextThatDoesNotWork {
bytes32 text;
uint reads;
address addr;
}
I have seen many examples doing this exact same thing. Example: Solidity Docs
But when I do this, my functions break.
What happens when I try the above
What works
So, in my contract I have a Text array:
TextThatWorks[] public textArray;
And I have a function to recall the texts inside this array, which returns arrays:
function listTexts () public view returns (bytes32[], uint[]) {
bytes32[] memory texts = new bytes32[](textArray.length);
uint[] memory readsArray = new uint[](textArray.length);
for (uint i = 0; i < textArray.length; i++){
texts[i] = textArray[i].text;
readsArray[i] = textArray[i].reads;
}
return (texts, readsArray);
}
This returns a nice array in the format [["some hexadecimal example"],[12]]
What does not work
The second struct, TextThatDoesNotWork
, only differs of TextThatWorks
because it has an address
field.
When I use it, my listTexts()
function stops working. It always returns empty arrays like [[],[],[]]
To accomodate the additional field, my listTexts()
function becomes the following:
function listTexts () public view returns (bytes32[], uint[], address[]) {
bytes32[] memory texts = new bytes32[](textArray.length);
uint[] memory readsArray = new uint[](textArray.length);
address[] memory addresses = new address[](textArray.length);
for (uint i = 0; i < textArray.length; i++){
texts[i] = textArray[i].text;
readsArray[i] = textArray[i].reads;
addresses[i] = textArray[i].addr;
}
return (texts, readsArray, addresses);
}
How I fill the array
function put(bytes32 _text, uint _reads) public returns (uint){
return textArray.push(TextThatDoesNotWork({
text: _text,
reads: _reads,
addr: msg.sender
}))-1;
}