Created
August 10, 2018 20:43
-
-
Save ripter/467baf295916295721c3fb52a0f62b72 to your computer and use it in GitHub Desktop.
Storage vs Memory in Solidity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From: https://cryptozombies.io/en/lesson/2/chapter/7 | |
contract SandwichFactory { | |
struct Sandwich { | |
string name; | |
string status; | |
} | |
Sandwich[] sandwiches; | |
function eatSandwich(uint _index) public { | |
// Sandwich mySandwich = sandwiches[_index]; | |
// ^ Seems pretty straightforward, but solidity will give you a warning | |
// telling you that you should explicitly declare `storage` or `memory` here. | |
// So instead, you should declare with the `storage` keyword, like: | |
Sandwich storage mySandwich = sandwiches[_index]; | |
// ...in which case `mySandwich` is a pointer to `sandwiches[_index]` | |
// in storage, and... | |
mySandwich.status = "Eaten!"; | |
// ...this will permanently change `sandwiches[_index]` on the blockchain. | |
// If you just want a copy, you can use `memory`: | |
Sandwich memory anotherSandwich = sandwiches[_index + 1]; | |
// ...in which case `anotherSandwich` will simply be a copy of the | |
// data in memory, and... | |
anotherSandwich.status = "Eaten!"; | |
// ...will just modify the temporary variable and have no effect | |
// on `sandwiches[_index + 1]`. But you can do this: | |
sandwiches[_index + 1] = anotherSandwich; | |
// ...if you want to copy the changes back into blockchain storage. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment