Functions

Syntax
Function :
   FunctionQualifiers fn IDENTIFIER
      ( FunctionParameters? )
      FunctionReturnType?
      : NEWLINE
      INDENT
      FunctionStatements*
      DEDENT

FunctionQualifiers :
   pub?

FunctionStatements :
         ReturnStatement
      | VariableDeclarationStatement
      | AssignStatement
      | AugmentedAssignStatement
      | ForStatement
      | WhileStatement
      | IfStatement
      | AssertStatement
      | EmitStatement
      | PassStatement
      | BreakStatement
      | ContinueStatement
      | RevertStatement
      | Expression

FunctionParameters :
   self? | self,? FunctionParam (, FunctionParam)* ,?

FunctionParam :
   IDENTIFIER : Type

FunctionReturnType :
   -> Type

A function definition consists of name and code block along with an optional list of parameters and return value. Functions are declared with the keyword fn. Functions may declare a set of input variables as parameters, through which the caller passes arguments into the function, and the output type of the value the function will return to its caller on completion.

When referred to, a function yields a first-class value of the corresponding zero-sized function item type, which when called evaluates to a direct call to the function.

A function header ends with a colon (:) after which the function body begins.

For example, this is a simple function:

fn answer_to_life_the_universe_and_everything() -> u256:
    return 42

A function may accept self as a parameter. This gives the function the ability to read and mutate contract storage.

Example:

contract Foo:
    my_stored_num: u256

    pub fn my_pure_func():
        pass
        
    pub fn my_self_func(self):
        self.my_stored_num = 26