Lesson 7 - Functions
Functions allow you to organize code into reusable sections.
Instead of writing the same code repeatedly, you can put it inside a function.
Use the fn keyword to create a function. Then call the function to use it.
fn greet() {
println!("Hello!");
}
fn main() {
greet();
}
This would print “Hello!”.
To give a function information, we use parameters.
fn greet(name: &str) {
println!("Hello, {}!", name);
}
greet("Alex");
This would print “Hello, Alex!” since the function recieves “Alex” through the parameter name.
You can also have multiple parameters, simply seperate them with commas in the function header.
fn add(a: i32, b: i32) {
println!("{}", a + b);
}
add(5, 3);
Output:
8
To add a return type, use an arrow: ->
fn add(a: i32, b: i32) -> i32 {
a + b
}
let result = add(5, 3);
The -> i32 means the function returns an i32. The variable result would now equal 8.
You may notice that there is no semicolon after a + b. Omitting the semicolon on the expression implicitly returns the value of the expression.
The different between and expression and a statement is important. An expression evaluates to a value, while a statement performs an action and doesn’t return a value.
Adding a semicolon turns the expression into a statement. This allows for the value a + b to be returned without explicitly using the return keyword. You may still use the return keyword to explicitly return a value like this: return a + b;