HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to RustVariablesData TypesOperatorsStringsVectors (Vec)Conditions (if / match)Loops (for / while)FunctionsOwnership & Borrowing
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Vector & HashMap
🔁 Condition & Loop
🧩 Function
🔑 Ownership & Borrowing
Rust›Functions

Functions

fn definition, parameter/return types, and implicit return of the last expression.

Simple enough for a 5-year-old to understand

fn and return

Parameter types use :, return types use ->. The last expression (without ;) is returned automatically.

Example code
1
fn square(x: i32) -> i32 {
Takes i32, returns i32.
FunctionTakes i32, returns i32.
2
x * x
NO ; → this value is returned.
FunctionNO ; → this value is returned.
3
}
4
fn main() {
5
println!("{}", square(5));
25
Output / Input25
6
}
FunctionOutput / Input
💡 Hint: Do NOT put a semicolon ; at the end of the returned last expression: 'x * x' returns, 'x * x;' does not.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Write a function named addUp that takes two i32s and returns their sum; print addUp(8, 9).

🎯 Expected output: 17

Loading editor…

About this topic

In Rust, functions are defined with fn and writing parameter types is MANDATORY. The return type is also specified; when omitted, the function is assumed to return nothing. Type inference works inside the function body, not in the signature.

The unusual part of Rust is the return syntax. When the last expression in a function is written without a semicolon, it becomes the return value; writing return is not necessary. Adding a semicolon turns the expression into a statement and the function returns nothing — this is the most common mistake for beginners.

The ownership rule comes into play when passing parameters. Passing a value directly transfers ownership and the caller cannot use it anymore. If you want to keep using it, you need to pass a reference; this is the most common fix in Rust.

What you will learn

  • defining functions with fn
  • the effect of a semicolon on the return value
  • the difference between ownership transfer and borrowing
  • passing parameters with mutable references
  • returning errors with the Result type

When to use?

Take a reference if the function will only read the value; requesting ownership forces the caller to lose the value and is unnecessary.

Return a Result type if the function can fail. There are no exceptions in Rust; the error is part of the return value and the caller must handle it.

Common mistakes

Wrong

fn square(n: i32) -> i32 {
    n * n;
}

fn main() {
    println!("{}", square(4));
}

A semicolon at the end of the last expression turns it into a statement and the function returns nothing; the compiler gives an "expected i32, found ()" error and suggests removing the semicolon. In Rust, a semicolon is not just a separator, it is a meaningful token.

Correct

fn square(n: i32) -> i32 {
    n * n
}

fn main() {
    println!("{}", square(4));
}

Wrong

fn show(text: String) {
    println!("{}", text);
}

fn main() {
    let message = String::from("Hello");
    show(message);
    println!("{}", message);
}

Since the parameter takes over ownership, message cannot be used after the function; the compiler gives a "borrow of moved value: message" error. If the function only reads the value, it should take a reference; then ownership remains with the caller.

Correct

fn show(text: &str) {
    println!("{}", text);
}

fn main() {
    let message = String::from("Hello");
    show(&message);
    println!("{}", message);
}

Wrong

fn increase(value: &i32) {
    *value += 10;
}

fn main() {
    let mut total = 5;
    increase(&total);
    println!("{}", total);
}

Ordinary references are read-only; overwriting them causes a compilation error. To modify, both the reference and the value must be mutable. In Rust, mutation permission is clearly visible in both the definition and the call — anyone reading the code can understand which function modifies what from the signature.

Correct

fn increase(value: &mut i32) {
    *value += 10;
}

fn main() {
    let mut total = 5;
    increase(&mut total);
    println!("{}", total);
}

Frequently asked questions

should I use return, or the last expression?

The last expression is the idiomatic way in Rust and is considered more readable. return is only used when you need to exit a function early — such as returning immediately when a condition is not met. The two are functionally identical.

Can a function return multiple values?

Yes, by returning a tuple. On the caller side, it is unpacked into separate variables using pattern matching. If the values form a meaningful whole, returning a struct with named fields is more readable.

How are errors returned?

With a Result type: the function returns either the success value or the error, and the caller must handle both. There are no exceptions in Rust, so the error path cannot be forgotten. The question mark operator reduces propagating errors upward to a single character.

Summary

Writing parameter and return types is mandatory.

The last expression becomes the return value when written without a semicolon.

Passing a value directly transfers ownership; references are passed for reading.

References must be mutable in order to modify the value.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code