January 2018
Beginner to intermediate
454 pages
10h 8m
English
We had a brief introduction to functions when we saw the main function. Let's see how to create functions with parameters and a return value.
Here's how to write a function that returns the maximum of two numbers:
fn max(a: i32, b: i32) -> i32 { if a > b { a } else { b } }
The parameters are between parentheses and must be explicitly typed since the type inference only infers the types of local variables. This is a good thing since this acts as a documentation. Moreover, this can prevent bugs when we change how we use the parameters or change the value that is returned. The function can be defined after it is used without any issue. The return type is after ->. When we return (), we can omit the -> and type.
The last expression ...
Read now
Unlock full access