Functions in Rust

Functions are central in Rust. We’ll learn about functions with a few different examples.

fn main() {
    // Call a function just as you'd expect, with
    // name(args).
    let res = plus(1, 2);
    println!("1+2 = {}", res);

    let res = plus_plus(1, 2, 3);
    println!("1+2+3 = {}", res);
}

// Here's a function that takes two i32s and returns
// their sum as an i32.
fn plus(a: i32, b: i32) -> i32 {
    // Rust allows implicit returns for the last expression
    // in a function if you omit the semicolon.
    a + b
}

// In Rust, you need to specify the type for each parameter.
// There's no shorthand for multiple parameters of the same type.
fn plus_plus(a: i32, b: i32, c: i32) -> i32 {
    a + b + c
}

To run the program:

$ rustc functions.rs
$ ./functions
1+2 = 3
1+2+3 = 6

There are several other features to Rust functions. One is multiple return values, which we’ll look at next.

Key differences from the original:

  1. In Rust, the main function is defined without parameters.
  2. Rust uses println! macro instead of fmt.Println.
  3. Rust function declarations start with fn instead of func.
  4. Rust uses -> to specify the return type, placed after the parameter list.
  5. Rust allows implicit returns for the last expression in a function if you omit the semicolon.
  6. In Rust, you need to specify the type for each parameter. There’s no shorthand for multiple parameters of the same type.
  7. Rust uses i32 as the default integer type, similar to int in the original.
  8. Variable declarations in Rust use let keyword.

The structure and explanation have been maintained, but adapted to Rust’s syntax and conventions.