When do you use return statement?

contract SimpleContract{
    
    string public myString;
    
    function setString(string memory _string) public returns(string memory) {
        myString = _string;
        return myString;
    }}  

and

contract SimpleContract{    
    string public myString;
    
    function setString(string memory _string) public {
        myString = _string;            
    }}  

:computer: Environment

:memo:Details
What is the difference between the two functions. When do you use return?

:1234: Code to reproduce

1 Like

Hi @Altaergo,

We should return if we want to read data externally such as in a public view function (see retrieve below) or we have a public function that we are using in other contracts that we want to use the value from.

// contracts/Box.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract Box {
    uint256 private value;

    // Emitted when the stored value changes
    event ValueChanged(uint256 newValue);

    // Stores a new value in the contract
    function store(uint256 newValue) public {
        value = newValue;
        emit ValueChanged(newValue);
    }

    // Reads the last stored value
    function retrieve() public view returns (uint256) {
        return value;
    }
}
2 Likes

Thanks :slightly_smiling_face:

1 Like