1
pragma solidity ^0.8.0;

contract Crud {

    struct Users{
        uint id;
        string name;
    }

    Users[] users; // this is type storage
    uint length = 0;

    function addUser(string memory _name) public{
        users.push(Users(length,_name));
        length++;
    }

    function getUser(uint _index) view public returns(Users memory){
        return users[_index];
    }
}

I have this basic code.

In getUser function why is it expecting the return type of Users as memory? It will return users and that is type storage.

1 Answer 1

0

I believe what will happen here is the function will copy the values from the Users struct from storage to memory before return. I don't believe you can return storage directly from a public view function anyway since it could go to another contract.

2
  • But if that is true then it will always type memory right? And we will never need any other type. ( I am new to this ). In that case, what is the need to define it if it is always the same? May 19, 2022 at 7:45
  • 1
    the return type can be declared as storage in internal functions, which will make them cheaper as the data does not need to be copied
    – gellej
    Oct 5, 2022 at 16:19

Your Answer

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

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