Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

Rust Functions


Functions

A function is a block of code that only runs when you call it.

Functions are used to organize your code, avoid repeating yourself, and make your program easier to understand.


Creating a Function

To create a function, use the fn keyword, followed by the function name and a set of parentheses () and curly braces {}:

Example

fn function_name() {
  // code to be executed
}

Calling a Function

Now that you have created a function, you can execute it by calling it.

To call a function, write the name of the function followed by two parantheses ().

Example

// Create a function
fn say_hello() {
  println!("Hello from a function!");
}

say_hello(); // Call the function
Try it Yourself »

Functions with Parameters

You can send information into a function using parameters. Parameters are written inside the parentheses ().

Example

fn greet(name: &str) {
  println!("Hello, {}!", name);
}

greet("John");
Try it Yourself »

In this example, the function takes a string parameter called name and prints it in the greeting message.


Functions with Return Values

A function can also return a value.

Use the  -> symbol in the function header to show what type of value will be returned.

Inside the function, use the return keyword to send the value back:

Example

fn add(a: i32, b: i32) -> i32 {
  return a + b;
}

let sum = add(3, 4);
println!("Sum is: {}", sum);
Try it Yourself »

This function adds two numbers and returns the result.

In Rust, you can omit the return keyword. Just write the value on the last line of the function, without a semicolon:

Example

fn add(a: i32, b: i32) -> i32 {
  a + b
}

let sum = add(3, 4);
println!("Sum is: {}", sum);
Try it Yourself »

The last line a + b is automatically returned.

Both examples do the same thing. It is up to you which one to use.


Why Use Functions?

  • To organize your code
  • To avoid repeating the same code
  • To make your programs easier to read and change

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.