DEV Community

Cover image for Functions in Rust
Daniel
Daniel

Posted on

Functions in Rust

Like other programming languages, functions are prevalent in Rust. One of the functions is the main function, which is the entry point of many programs. The fn keyword is used to declare a function.
Here is an example of a function:

fn main() {
    println!("Hello World!");
}

Enter fullscreen mode Exit fullscreen mode

Parameters

We can define functions to have parameters, which are special variables that are part of a function’s signature. You can think of a function parameter as a tuple that can accept as many parameters of multiple data types as you wish. You must declare the type of each parameter.
Here is an example:

fn main() {
    another_function(5);
}

fn another_function(x: i32) { //you must declare the type of each parameter
    println!("The value of x is {x}");
}
Enter fullscreen mode Exit fullscreen mode

The declaration of another_function has one parameter named x. The type of x is specified as i32 when we pass 5 into another_function, the println! macro puts 5 where the pair of curly brackets containing x was in the format string.
Here is the output of the code above:

$ cargo run
   Compiling functions v0.1.0 (file:///projects/functions)
    Finished dev [unoptimized + debuginfo] target(s) in 1.21s
     Running `target/debug/functions`
The value of x is: 5
Enter fullscreen mode Exit fullscreen mode

Statements and Expressions

A statement is a line of code that ends with a semi-colon and does not evaluate to some value. An expression, on the other hand, is a line of code that does not end with a semi-colon and evaluates to some value.
Here is an example of a statement:

let x = 15;
Enter fullscreen mode Exit fullscreen mode

Functions with Return Values

Functions can return values to the code that calls them. We don’t name return values, but we must declare their type after an arrow (->). You can explicitly use the return keyword to return a value, but most functions implicitly return the last expression.
Here’s an example of a function that returns a value:

fn main() {
    let x = sum(4);
    println!("The value of x is {x}");
}

fn sum(y: i32) -> i32 {
    y+2
} 
Enter fullscreen mode Exit fullscreen mode

Example with return:

fn main() {
    let x = sum(4);
    println!("The value of x is {x}");
}

fn sum(y: i32) -> i32 {
    return y+2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)