How to fetch value from dynamic array push function? Below is the code of pushing function, but how will I fetching that array values?
contract PushStruct {
struct MyStruct {
uint field1;
uint field2;
}
MyStruct[] public myStructs;
function pushStruct()
public
{
MyStruct memory m;
m.field1 = 1;
m.field2 = 2;
myStructs.push(m);
}
}
For Example:
function valuereturn() view public returns(uint){
for(uint n=0;n<myStructs.length;n++){
myStructs storage f = MyStruct[n];
return (f.field2);
}
}
When I am trying to run the above code, getting complilation error (Error : TypeError: Storage location can only be given for array or struct types..) Can you please explain how to figure out this issue? Help will be appreciated.
returnstatement inside aforloop? What exactly are you expecting to happen??? The function will return at the end of the first iteration, hence the rest of the loop is meaningless! – goodvibration Mar 18 '19 at 09:31function myStructs(uint index) public view returns (uint, uint). So there's nothing for you to do. You can add a function to returnmyStructs.length, which will make it easier for you to handle things in an off-chain script. – goodvibration Mar 18 '19 at 09:48myStructs[n]instead ofMyStruct[n], and should beMyStruct storage finstead ofmyStructs storage f. And you method stops after returning value from the first struct. Is this desired? – Mikhail Vladimirov Mar 18 '19 at 12:50