Sub topic 1
Defining and Calling Functions
Functions are the basic unit of code reuse in Rust. This chapter covers how to declare a function, how to call it, and the rules the compiler enforces on both. Later chapters build on this one: statements and expressions, parameters and return values, and control flow.
Prerequisites
This chapter assumes you can do the following:
- Create a project with
cargo newand run it withcargo run. - Read basic Rust syntax and use primitive types such as
i32,bool, and&str. - Declare variables with
letandlet mut.
You do not need to know about ownership, traits, or generics yet. Where they appear, the chapter points forward instead of explaining them.
The anatomy of a function
A Rust function is declared with the fn keyword, a name, a parameter list in parentheses, an optional return type after ->, and a body in braces.
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let sum = add(2, 3);
println!("{sum}");
}Running this program prints 5.
The parts are:
fn adddeclares a function namedadd.(a: i32, b: i32)is the parameter list. Each parameter has a name, a colon, and a type.-> i32is the return type. It states that the function produces ani32.- The body is a block. Its last expression,
a + b, has no semicolon, so its value becomes the return value.
main is the entry point of a binary crate. It takes no parameters and, in its simplest form, returns (), the unit type. A function with no -> clause also returns ().
Naming conventions
Rust uses snake_case for function names: lowercase words separated by underscores. The compiler does not reject other styles, but it emits a non_snake_case warning. Following the convention makes your code match the standard library and nearly every crate you will read.
Calling a function
A call is the function name followed by arguments in parentheses. The arguments are matched to parameters by position. Rust has no named arguments and no default values, so every call must supply exactly the declared number of arguments.
fn greet(name: &str, times: u32) {
for _ in 0..times {
println!("Hello, {name}!");
}
}
fn main() {
greet("Ferris", 2);
}This prints the greeting twice. greet has no ->, so it returns (), and the call is used as a statement.
Parameters are always typed
Rust does not infer parameter types or return types for named functions. You write them out. This is deliberate. A function signature is a contract. The compiler checks the body against it, and callers check their calls against it without looking inside the body.
Inside a function body, types of local variables are still inferred as usual. Only the signature must be explicit.
Argument count and type errors
The compiler checks every call against the signature. Both of the following calls fail to compile.
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let x = add(1);
let y = add(1, "2");
}The first call gives error E0061 because the function takes 2 arguments but 1 was supplied. The second gives a mismatched types error because "2" is a &str, not an i32. Rust never converts between numeric types or strings implicitly when you call a function.
Order of definition does not matter
You can call a function before the point in the file where it is defined. Rust resolves names across the whole module, not top to bottom.
fn main() {
println!("{}", square(6));
}
fn square(n: i32) -> i32 {
n * n
}Many programmers put main first and helpers below it. Others do the reverse. Pick one and stay consistent within a project.
Return values and the unit type
A function that returns nothing in particular returns the unit type (). You can write -> (), but by convention you leave it out.
Compare the two functions below.
fn shout(s: &str) {
println!("{}!", s.to_uppercase());
}
fn length(s: &str) -> usize {
s.len()
}
fn main() {
shout("hi");
let n = length("hello");
println!("{n}");
}shout is called for its side effect, printing. length is called for its result. If you ignore the result of a function that returns a value, the compiler is usually silent. It warns only when the returned type is marked #[must_use], as Result is.
The return value is the last expression
The final expression in a block, written without a trailing semicolon, is the value of the block. For a function body, that is the return value. A common beginner error is adding a semicolon.
fn broken(x: i32) -> i32 {
x + 1;
}
fn main() {
println!("{}", broken(1));
}This fails with a mismatched types error. With the semicolon, x + 1; becomes a statement, and the block's value becomes (). The signature promises an i32. The compiler's message even suggests removing the semicolon.
The next chapter covers the statement and expression distinction in detail. For now, remember this rule: no semicolon on the last line means "return this value".
You can also leave a function early with the return keyword, which a later chapter covers.
Nested functions and scope
You can define a function inside another function's body. The inner function is visible only inside that body.
fn describe_sum(a: i32, b: i32) -> String {
fn add(x: i32, y: i32) -> i32 {
x + y
}
format!("{a} + {b} = {}", add(a, b))
}
fn main() {
println!("{}", describe_sum(2, 3));
}An inner fn does not capture variables from the enclosing function. Notice that add takes its inputs as parameters instead of reading a and b directly. Capturing local variables is the job of closures, which a later chapter covers.
Visibility
By default, a function is private to the module that defines it. Prefix it with pub to make it visible to other modules.
mod math {
pub fn double(x: i32) -> i32 {
helper(x)
}
fn helper(x: i32) -> i32 {
x * 2
}
}
fn main() {
println!("{}", math::double(21));
// math::helper(21); // error: function `helper` is private
}You call a function in another module with a path, using :: between the module name and the function name. The main function can call math::double but not math::helper. Modules are outside the scope of this chapter, but pub appears in nearly every real program.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `expected i32, found ()` | A semicolon after the last expression | Remove the semicolon |
| `this function takes 2 arguments but 1 argument was supplied` | Wrong argument count | Match the signature |
| `expected X, found Y` on an argument | Wrong argument type | Convert explicitly, for example with `as` or `.into()` |
| `missing type for function argument` or a similar parse error | A parameter without a type annotation | Add `: Type` |
| `function is private` | Calling a non-`pub` function from another module | Add `pub` or move the call |
| Warning `non_snake_case` | Name such as `addNumbers` | Rename to `add_numbers` |
How a call flows
When main calls add, the arguments are evaluated first, in order, from left to right. Then control moves into add. The body runs, and the final expression's value is handed back to the caller.
For simple integer arguments like these, each argument is copied into the parameter. That is why the caller can still use its own values afterward. For types that own heap data, such as String, passing the value moves it into the function. A later chapter in this tutorial covers passing references, which avoids that move.
Summary of rules
- Use
fn name(param: Type, ...) -> ReturnType { body }. - Write every parameter type and the return type. Omitting
->means the function returns(). - Leave off the semicolon on the last expression to return its value.
- Function names use
snake_case. - Functions can be called before their definition appears in the file.
- Functions are private unless marked
pub. - Rust has no overloading, no default arguments, and no named arguments. Two functions in the same module cannot share a name.
Exercise
The function below fails to compile. Explain why, and fix it with the smallest possible change. fn area(width: u32, height: u32) -> u32 { width * height; }
Show answer
The semicolon turns width * height into a statement, so the function body evaluates to () instead of a u32, which conflicts with the declared return type. Remove the semicolon: width * height.
Exercise
A colleague writes let total = add(1, 2, 3); for a function declared as fn add(a: i32, b: i32) -> i32. What happens, and what are two ways to resolve it?
Show answer
The compiler reports error E0061 because the function takes 2 arguments but 3 were supplied. Either call it with two arguments, for example add(add(1, 2), 3), or change the function signature to accept a third parameter and update every other call.