Functions

We've already discussed functions a bit, but let's do a bit more digging. As of right now, we've only seen the main function. But let's create another function:

main.rs
fn main() {
  println!("Hello, world!");
  another_function();
} 

fn another_function() {
  println!("Another function.");
}

This will print out:

Hello world!
Another function.

As alluded to the section Hello World, Rust functions can have parameters but the parameters must have a type.

main.rs
fn main() {
    another_function(5);
}

fn another_function(x: i32) {
    println!("The value of x is: {}", x);
}

If a function has a return value, then it's type also must be declared.

You might have noticed that x + 1 didn't have a semicolon after it. That is because it is an expression and not a statement. Per the Rust book:

Statements are instructions that perform some action and do not return a value. Expressions evaluate to a resulting value. Let’s look at some examples.

Let's clarify that with some sample code:

Last updated