How To Code Functions In Rust: The fn Keyword

Jan 15, 2022

How to use the fn keyword

The keyword fn is used to declare functions in Rust:

fn main() {
    println!("this is a function!");
}

How to call a function

You can a function in other functions using its name:

fn function1() {
    println!("this is function1!");
}

fn function2() {
    function1();
}

How to use parameters in a function

You can add parameters to a function:

fn function1(param1: i32, param2: char) {
    println!("The parameters are: {}{}", param1, param2);
}

How to return a value in a function

A function can also output a result:

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

Need a technical writer with years of programming experience for your tech business? Hire me at Embarque