Functions
Programming Languages · Rust Basics · 12 min
Write your own functions with typed parameters and return values.
Your own function
A function is a named block of code you can run again and again. Make one with fn, outside main. Run it ("call" it) by writing its name and ():
fn wave() {
println!("Hi!");
}
fn main() {
wave();
}
Above
main, write a functioncheerthat printsGo team!.Call
cheertwice frommain.
Parameters
A parameter is a value you hand to a function. List them in the brackets, each with a name and a type:
fn greet(name: &str) {
println!("Hello, {}!", name);
}
Now greet("Ada") prints Hello, Ada! and greet("Linus") prints Hello, Linus!. Rust always wants the types written here.
Write
fn say_age(name: &str, age: u32)that prints the name,is, and the age, likeAda is 36.In
main, callsay_age("Ada", 36)and thensay_age("Linus", 54).
Returning a value
Functions can hand a value back. Write the type after ->. The last line, with no semicolon, is the value that comes back:
fn double(n: i32) -> i32 {
n * 2
}
Then double(4) gives 8, which you can print or store.
Write
fn add(a: i32, b: i32) -> i32that returnsa + b.In
main, printadd(2, 3)and thenadd(10, 20).
Expressions: the missing semicolon
Why no semicolon? In Rust, n * 3 is an expression: it produces a value. Add a ; and it becomes a statement, which produces nothing, so the function has nothing to return.
You can write return n * 3;, but Rust programmers usually just leave the last expression bare. It's shorter.
Rewrite
tripleso its body is justn * 3, with noreturnand no semicolon.Write
fn square(n: i32) -> i32in the same style (bodyn * n), then printsquare(5)inmain.
Put it together: a tip calculator
Two small functions that work together. total can call tip to do part of its job. Functions calling functions is how big programs are built.
Write
fn tip(amount: f64) -> f64that returnsamount * 0.25.Write
fn total(amount: f64) -> f64that returnsamountplustip(amount).In
main, printTip: 12andTotal: 60by callingtip(bill)andtotal(bill).
More in Rust Basics
Previous: Data Types · Next: Control Flow