0.2 Functions

Variables in Rust can also store functions for repeated use. Functions are little programs on their own that can take inputs, perform more or less complex transformations on the inputs and produce outputs. The inputs of a functions are called parameters. They are defined using two pipe | symbols, with the parameters listed between them. The body of the function follows, enclosed in curly braces {} if it contains multiple statements. The last expression of the function body is its return value i.e. the value the function produces. Functions that end with a statement don't return anything. Functions get executed (or »called«) by using their name followed by parentheses (), with the arguments provided between them.

// a function taking text input
let greet = |greeting, name| format!("{greeting}, {name} 👋");

println!("{}", greet("Hello", "World"));
println!("{}", greet("Привіт", "світе"));
println!("{}", greet("こんにちは", "世界"));

format!() is a command that creates text from other expressions. It works similarly to print!(), but instead of printing the text to the screen, it produces the text as a value that can be used later.

Just like variables and expressions, functions can be combined in many ways. They can also be used to create more complex functions:

// three functions taking numeric input
let double = |x| x * 2;
let square = |x| x * x;
let double_square = |x| {
    // first square, then double
    let y = square(x);
    double(y)
};

println!("{}", double(3));
println!("{}", square(4));
println!("{}", double(double(5))); // double, then double again
println!("{}", square(double(5))); // first double, then square
println!("{}", double(square(7))); // first square, then double
println!("{}", double_square(7));

Functions, operators and macros

Functions are not the only way to perform operations in Rust. We have already seen operators like +, -, * and / that can be used to perform arithmetic operations. Macros look similar to functions but always end with an exclamation mark !. They often (but not always) produce values and can be used as expressions. For now we'll just use some macros provided by Rust but later we will also learn how to create our own macros.

winfried2026-01-16 13:46:43.105279000