0

I still don't really understand the use of memory and storage in solidity. I have written a simple code to store information from books indexed by a key, as in the example below. Since I'm using a mapping, the compiler throws an error if I try to declare books as storage. But he forces me to declare the new book as a memory. Apparently the code works, but I don't understand what is happening behind the scenes. Is the books array a storage-type variable? and what is it referencing to, exactly? Grateful if anyone can explain.

pragma solidity >=0.7.0 <0.9.0;

contract RegisterBook {

struct Book {
    string info1;
    string info2;
}

mapping(string => Book) public books;


function registerBook(string memory info1, string memory info2, string memory key) public returns (bool success) {

    Book memory newBook;
    newBook.info1 = info1;
    newBook.info2 = info2;
    books[key] = newBook;

    return true;
}

}

  • I explained here : https://stackoverflow.com/questions/33839154/in-ethereum-solidity-what-is-the-purpose-of-the-memory-keyword/69199728#69199728 – Yilmaz Jan 09 '22 at 06:27

1 Answers1

1

Well, long history short, memory as the name says is just the memory, all the variables declared inside a function and the structs declared as memory are stored there and after every execution the memory is cleaned up, you can think on it like a ram, and the storage is the "permanent storage" you can think of it like a hard drive, all the variables that are declared outside of a function are stored there, the storage values are stored in the storage slots, each one of the storage slots have 32 bytes available, remember that each write on one storage variable cost more than in a memory variable, so try to limit their use if you can

jhonny
  • 805
  • 4
  • 10