Deviacavatar

deviac

28 October 2016


Rust Functions


functions.md

Every Rust program has at least one function, the main function:

fn main() {
}

This is the simplest possible function declaration. As we mentioned before, fn says ‘this is a function’, followed by the name, some parentheses because this function takes no arguments, and then some curly braces to indicate the body. Here’s a function named foo:

fn foo() {
}

So, what about taking arguments? Here’s a function that prints a number:

fn print_number(x: i32) {
    println!("x is: {}", x);
}

Here’s a complete program that uses print_number:

fn main() {
    print_number(5);
}

fn print_number(x: i32) {
    println!("x is: {}", x);
}

As you can see, function arguments work very similar to let declarations: you add a type to the argument name, after a colon.

Here’s a complete program that adds two numbers together and prints them:

fn main() {
    print_sum(5, 6);
}

fn print_sum(x: i32, y: i32) {
    println!("sum is: {}", x + y);
}

You separate arguments with a comma, both when you call the function, as well as when you declare it.

Unlike let, you must declare the types of function arguments. This does not work:

fn print_sum(x, y) {
    println!("sum is: {}", x + y);
}

You get this error:

expected one of `!`, `:`, or `@`, found `)`
fn print_sum(x, y) {

This is a deliberate design decision. While full-program inference is possible, languages which have it, like Haskell, often suggest that documenting your types explicitly is a best-practice. We agree that forcing functions to declare types while allowing for inference inside of function bodies is a wonderful sweet spot between full inference and no inference.

What about returning a value? Here’s a function that adds one to an integer:

fn add_one(x: i32) -> i32 {
    x + 1
}

Rust functions return exactly one value, and you declare the type after an ‘arrow’, which is a dash (-) followed by a greater-than sign (>). The last line of a function determines what it returns. You’ll note the lack of a semicolon here. If we added it in:

fn add_one(x: i32) -> i32 {
    x + 1;
}

We would get an error:

error: not all control paths return a value
fn add_one(x: i32) -> i32 {
     x + 1;
}

help: consider removing this semicolon:
     x + 1;
          ^

This reveals two interesting things about Rust: it is an expression-based language, and semicolons are different from semicolons in other ‘curly brace and semicolon’-based languages. These two things are related.

See more: https://doc.rust-lang.org/book/


Share This Post