0

I'm having an issue where when I try to change a struct objects value that is stored in my mapping, it doesn't permanently / globally change it, it only appears to change it locally.

In my example code below, I have a struct 'Test', a mapping 'testMap' of uint => 'Test' and 2 methods. I first call setMap(), where I put a mapping key of 1 to and set the nmbr member of the 'Test' struct to 4. I then call checkMap() and basically check what that member 'nmbr' is equal too.

The first time I call checkMap() (after calling setMap()), it returns 5 which indicates it went into the first if statement as it should, and set the 'nmbr' member to '5' as it should. When I call it checkMap() the second time 'nmbr' should now be equal to '5' therefore the first 'if' should evaluate to false, and the 'else if' should evaluate to true and return 34. However it still returns '5' meaning it never entered the second 'if' statement.

My question is why/how to get this desired functionality to work. Are mappings somewhat read-only after the values are set? I say somewhat because it lets me change the value locally in the function (because it returns '5' not '4') but doesn't appear to actually change the value.

Thanks in advance for any help ! Please let me know if you need anymore information for this question.

 struct Test {
   uint nmbr;
 }

 mapping(uint => Test) testMap;

 function setMap() public payable {

   testMap[1].nmbr = 4;

 }

 uint theResult = 99;

 function checkMap() public returns (uint) {

   if(testMap[1].nmbr == 4) {
       testMap[1].nmbr = 5;
       theResult = testMap[1].nmbr;
   } else if(testMap[1].nmbr == 5) {
       theResult = 34;
   }

   return theResult;
}
  • 1
    how are you testing your code? I just tried it in remix and is working well. First time will return 5 second time 34 – mirg Apr 27 '18 at 2:47
  • @mirg Thanks for the reply! And that's strange, I am testing it on Ganache as a private blockchain and Truffle – savard Apr 27 '18 at 2:55
  • My guess would be that you're calling checkMap instead of sending a transaction. Note that transactions don't have return values. (Remix will show the return values of functions called via a transaction, but an actual blockchain does not record any sort of return value for a transaction.) – smarx Apr 27 '18 at 3:56
  • @smarx Thanks for the reply ! I was using some web3.js to first send a transaction/call setMap() then in a callback in the web3.js called checkMap(), I then called checkMap() a second time which still returned 5. I haven't figured out exactly what I'm doing wrong however I've realized this won't work for what I need to do even if it was working. Thanks ! – savard Apr 27 '18 at 7:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.