...by Daniel Szego
quote
"Simplicity is the ultimate sophistication."
Leonardo da Vinci

Saturday, January 13, 2018

Solidity and Truffle Tips and Tricks - passing struct argument by reference


In solidity the structs given as parameters for a function are mostly given by value, meaning that the whole struct is practically duplicated in memory and handled as a local copy of the original struct. There is one exception that you can use if you want to use another semantics: with internal and private functions you can use the storage keyword to make sure that the struct us handled as reference and not as value. 

contract StructTestContract {
    
  struct TestStruct{
     uint a;
  }
    
  TestStruct public myStruct= TestStruct(1);
    
  function copyStructByValue(TestStruct _struct){
     _struct.a = 2;
  }

 function copyStructByReference(TestStruct storage _struct) internal{
     _struct.a = 2;
  }

 function testCopyStructByValue(){
    copyStructByValue(myStruct);
 }

 function testCopyStructByReference(){
    copyStructByReference(myStruct);
 }
}

In the previous example, copyStructByReference has got a real reference to the TestStruct resulting 2 after the function call, as copyStructByValue simply copies the whole struct meaning that the original value will not change.