Trusted answers to developer questions

How to write functions in Rust

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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.
Parts of a function
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 ©2024 Educative, Inc. All rights reserved
Did you find this helpful?