0
contract Shopping {

    struct Article {
        uint id; 
        address seller;
        address buyer;
        string name;
        string description;
        uint256 price;
    }

    // state variable 
    mapping(uint256 => Article) public articles; 
    uint articleCounter;

    function buyArticle(uint _id ) public payable {
        Article  storage article = articles[_id];
        require( article.buyer == 0x0);                                      
        require(msg.sender != article .seller]);
    }
}

1) I have got this code in online

2) i am wondering why storage is declared rather than memory

3) For getting values from mapping articles[] i used slicing technique which is similar to array slicing

4) But Now in storage type we are using article.buyer rather than article[buyer]

1 Answer 1

1

1) I have got this code in online

Just in case it isn't clear, you can run your contracts on your own chain or a simulator like ganache-cli or even Remix to start so dev doesn't cost money with each iteration.

2) i am wondering why storage is declared rather than memory

They mean different things. storage will create a pointer to values in a storage, known as a reference variable. memory will copy the values from storage to a new memory variable. It would make quite a difference if the contract was updating storage values. In this case, the difference is this way is slight cheaper on gas.

For more on the difference and a warning, have a look over here: https://vessenes.com/solidity-frustrations-references-and-mapping/

4) But now in storage type we are using article.buyer rather than article[buyer]

Storage and memory types don't change this syntax.

You use mapping(uint256 => Article) public articles; which means there is a struct at each index. The struct contains members. So, you can say

Article storage myArticle = articles[myArticleId]
string n = myArticle.name;

or you can say

string n = articles[myArticleId].name;

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.