contract Helloworld {
uint private simpleInt;
function getValue() public view returns (uint) {
return simpleInt;
}
}
What is the difference between "return" and "returns", I am a beginner.
The difference is that returns (uint)
is defining the function as having 1 return variable, which is a uint. Related, but separate, is the statement return simpleInt;
, which is actually returning simpleInt
from the function.
There are two concepts in functions.
return
statementreturns
keywordreturn
This is your standard return
statement. Whatever is written after it is returned from the function.
returns
function getValue() public view returns (uint) {
return simpleInt;
}
function getValue2() public view returns (uint simpleInt) { }
The first case simply defines a function signature.
On the other hand, getValue2()
also defines a name of the returned variable.
With this, it is possible to omit the return
statement - in this case completely omit the function body.
This boils down to the difference between the "fetch!" and "fetches" at the dog park. Respectively an order and a statement.
"return X" is an imperative AKA an order. Like in linguistics, it says "you (your function) better return that thing that needs returning and that's an order!".
This order is generally found at the very end of a function and means "now that you're done processing X, return it to whatever line of code called this function you're currently in".
Meanwhile, "returns X" is a declarative AKA a statement of a fact. Like in linguistics, it is a statement that "this thing (your function) is expected to return something once it's done doing its thing.
This statement is found in the declaration of a function (your very first line of code) and means "once done, this function returns one or more things of the following types to whoever called this function in the first place".
So if you're declaring a function and you want whoever reads your code (including and especially your future self) to know at a glance what this function returns, then declare/state what that returned thing is right at the top:
function myFunction
returns (
typeOfMyThingReturnedByThisFunction easyToUnderstandNameOfMyThingReturnedByThisFunction
)
{
blah blah blah the body of my function goes here, don't forget the semi-colon;
}
To actually cause the function to return the thing that this function is supposed to return, you issue an order by telling the function "hey, function, return the thing I want you to return!" as follows:
function myFunction
returns (
typeOfMyThingReturnedByThisFunction easyToUnderstandNameOfMyThingReturnedByThisFunction
)
{
return easyToUnderstandNameOfMyThingReturnedByThisFunction;
}
Example:
/* My function returnS a uint called theNumberFour which is probably the number 4 */
function myFunction returns (uint theNumberFour) {
/* "Hey, function, please return the number 4" */
return 4;
}