Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

return
statement
expression
parameter
arguments

How to write functions in Rust

Educative Answers Team

Like every other programming language, Rust has its own rules for declaring functions. Some syntax may seem familiar; however, there are some extra things to notice:

1. fn keyword

This keyword is placed before the name of the new function to indicate that a new function is being declared:

fn foo(){
    // Do something.
}

Curly braces {} are used to indicate the function’s body, like most other languages.

2. Type annotations

All the parameters of a Rust function must have their types declared in the function’s signature:

fn foo(a: i8, b: i8){
    // Both 'a' and 'b' are of type i8.
}

3. Return value

The return keyword can be used to return a value inside a function’s body. When this keyword isn’t used, the last expression is implicitly considered to be the return value. If a function returns a value, its return type is specified in the signature using -> after the parentheses ().

Statement vs. Expression

  • A statement does not return a value, so it cannot be used to assign a value to another variable. For example, in some languages, we may be allowed to write x = y = 5; but in Rust, let x = (let y = 5) is an invalid statement because the let y = 5 statement does not return a value that can be assigned to x.
  • Expressions can be a part of a statement.
  • When a semi-colon is written at the end of an expression,​ it turns into a statement and does not return a value.
  • {} blocks and function calls are expressions.
svg viewer
Parts of a function

Code

fn main() {
  let a = 10;
  
  println!("a = {}", foo(a));
}

fn foo(a: i8) -> i8 {
  if a > 0 {
    return 5;
  }
  else {
    a + 1
  }
}

RELATED TAGS

return
statement
expression
parameter
arguments
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring