Why this matters
Rust promises something that older systems languages cannot: memory safety without a garbage collector. The compiler tracks who owns each piece of data and rejects programs that would use freed memory, read past an array, or create data races. You get the speed and low-level control of C or C++, but whole categories of bugs are caught before your program ever runs.
That promise changes how you think. Instead of relying on discipline and debugging, you let the type system enforce rules at compile time. The borrow checker, as the responsible part of the compiler is called, can feel strict at first, but it is really a tireless reviewer pointing out exactly where your design is ambiguous about ownership. Once you work with it, many runtime crashes simply disappear.
Rust is used for command-line tools, web servers, game engines, browsers, and embedded devices. Its function model is where all of this begins. Parameters declare ownership or borrowing, return values use the final expression of a body, and generics and closures let you write flexible code that still compiles down to efficient machine instructions.
The big picture
Rust compiles to native code with no virtual machine and no runtime garbage collector. What makes it distinctive is that the compiler reasons about the lifetime and ownership of every value. When you call a function, the signature tells you whether you are giving the function ownership of a value or merely lending it a reference, and the compiler checks that you honor that agreement.
Functions in Rust are declared with the fn keyword. Each parameter has an explicit type, and the return type follows an arrow. The last expression in the body is the return value, which means Rust blurs the line between statements and expressions more than C does. An if branch or a block can itself produce a value, making code both concise and expressive.
When you pass a value, ownership usually moves into the function and the caller can no longer use the original. When you pass a reference with an ampersand, you only lend the value, and the compiler guarantees the reference cannot outlive the data it points to. Mutable references are even stricter: you may have exactly one, so simultaneous conflicting access is impossible by construction.
Core ideas
fn syntax
You declare a function in Rust with the fn keyword, followed by the name, a parenthesized parameter list, an optional return type, and a body in braces. Names use snake_case by convention. The function named main is the entry point of every executable program, and it runs when the program starts.
Rust does not care about the order in which you define functions, so you can call a helper that appears later in the file without a forward declaration. That is a pleasant change from C. Functions can be defined at the top level, inside modules, inside other functions, or as methods on types.
fn main() {
greet();
}
fn greet() {
println!("Hello from Rust!");
}
Watch out. Using camelCase for function names. Rust conventions call for snake_case, and while the compiler accepts other styles, your code will look out of place without it.
Parameters and types
Every parameter in a Rust function must have its type written explicitly, separated from the name by a colon. Multiple parameters are separated by commas. The compiler never infers parameter types from call sites the way some languages do, because each function must have a single, unambiguous signature that callers can rely on.
The return type comes after an arrow following the parameter list. If there is no return type, the function returns the unit type, written as empty parentheses, which is similar to void in C. In practice you simply omit the arrow and its type when a function returns nothing useful.
fn add(a: i32, b: i32) -> i32 {
a + b
}
Watch out. Forgetting the type annotation on a parameter. Rust reports a clear error, but it is a common slip when you are coming from a language that infers everything.
Return values
In Rust the final expression of a function body is its return value. You simply write the expression without a semicolon, and whatever it evaluates to flows out of the function. You can still use the return keyword for an early exit, which is handy in branches, but the idiomatic style is to let the last expression do the work.
This expression-oriented design makes functions read like a description of a value. A body containing several let statements can end with one bare expression that becomes the result. If you accidentally put a semicolon after that final expression, it becomes a statement returning the unit type, and the compiler will tell you the types do not match.
fn max(a: i32, b: i32) -> i32 {
if a > b { a } else { b }
}
Watch out. Adding a semicolon to the final expression when you meant to return it. Writing a + b; returns the unit type, not the number, so remove the semicolon.
Statements vs expressions
Rust distinguishes statements, which perform an action and produce no value, from expressions, which evaluate to a value. A let binding is a statement. An arithmetic operation, a function call, a block, and an if conditional are all expressions. Because blocks are expressions, you can use them anywhere a value is expected.
This is why you can write let number = if condition { 1 } else { 2 }; the whole conditional produces a value that is assigned to number. Both branches must return the same type. Embracing expressions lets you write compact code without sacrificing readability, and it is central to understanding how functions return values.
fn sign(n: i32) -> &'static str {
let label = if n < 0 { "negative" } else { "nonnegative" };
label
}
Watch out. Assuming an if without an else can produce a value in all cases. If one branch produces a value, every branch must, or the compiler will reject the mismatched types.
Ownership in calls
When you pass a value to a function by value, ownership moves into that function. The parameter becomes the new owner, and the original variable in the caller can no longer be used, because Rust guarantees there is exactly one owner for any piece of data. Moving is usually just a cheap transfer of a pointer and length, not a deep copy.
Some types implement the Copy trait, which means they can be duplicated trivially. Integers, booleans, and characters are Copy, so passing them by value leaves the original usable. A String is not Copy because it owns heap memory, so passing one by value moves it and the caller loses access.
fn consume(s: String) {
println!("{}", s);
}
fn main() {
let name = String::from("Ada");
consume(name);
// name cannot be used here
}
Watch out. Trying to use a variable after moving it into a function. Either pass a reference instead, or create a fresh value for the second use.
Borrowing and references
A reference lets you use a value without taking ownership. You create one with an ampersand, and the function parameter declares its type with an ampersand too. Borrowing is the Rust answer to passing by pointer, but with a crucial guarantee: the compiler proves the reference never outlives the value it points to.
By default references are immutable, so the function may read the value but not change it. You can have as many immutable references as you like at the same time, because readers cannot interfere with one another. This makes signatures like fn length(s: &String) -> usize safe and very common.
fn length(s: &String) -> usize {
s.len()
}
fn main() {
let text = String::from("hello");
println!("{}", length(&text));
}
Watch out. Forgetting the ampersand at the call site. Passing text instead of &text tries to move the String, so a function expecting a reference will not compile.
Mutable references
A mutable reference, written with an ampersand followed by mut, allows a function to modify the borrowed value. The variable being borrowed must itself be declared mut. The compiler enforces a strict rule: you may have either one mutable reference or any number of immutable references, but never both at the same time.
That exclusivity rule is what prevents data races and many classic bugs at compile time. If a function needs to change a value, give it a mutable reference and make sure no other reference is alive at that moment. After the mutable borrow ends, immutable borrowing is allowed again.
fn shout(s: &mut String) {
s.push('!');
}
fn main() {
let mut text = String::from("hey");
shout(&mut text);
}
Watch out. Trying to hold an immutable reference while taking a mutable one to the same value. The compiler rejects overlapping borrows, so end the first borrow before starting the second.
Lifetimes in functions
Every reference has a lifetime, the region of the program during which it is valid. Often the compiler can figure this out on its own through a process called elision, so you rarely write lifetimes in simple functions. When a function returns a reference, though, the compiler needs to know which input it borrows from.
You express that relationship with a lifetime parameter such as 'a. A signature like fn longest<'a>(a: &'a str, b: &'a str) -> &'a str says the returned reference is valid for as long as both inputs are. This prevents the function from returning a reference to a local value that would vanish on return.
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
Watch out. Returning a reference to a value created inside the function. Its lifetime ends when the function returns, so the compiler will refuse to let it escape.
Closures
A closure is an anonymous function you can store in a variable or pass to another function. It uses vertical bars for its parameters and can capture values from the surrounding scope. Rust infers the parameter and return types in most cases, so closures are pleasantly short to write.
Closures can capture by reference or by value, and the compiler chooses the least restrictive option it can. They implement the Fn family of traits, which is how higher-order functions such as map and filter accept them. When a closure outlives the scope it came from, Rust offers the move keyword to force capturing by value.
fn main() {
let add = |a: i32, b: i32| a + b;
println!("{}", add(2, 3));
}
Watch out. Assuming a closure can outlive a borrowed variable it captured. Use the move keyword to take ownership of captured values when the closure must live longer.
Generic functions
A generic function works over many types instead of one. You declare a type parameter in angle brackets and use it in the signature. Rust then compiles a separate version for each concrete type used, a process called monomorphization, which keeps the generated code fast with no runtime type checks.
When you need behavior from the type, you add a trait bound. A bound such as T: PartialOrd says the type must support comparison, which lets you write a generic max function that works for integers and floating-point numbers alike. Bounds describe capabilities rather than concrete types.
fn identity<T>(value: T) -> T {
value
}
fn main() {
let n = identity(42);
let s = identity(String::from("hi"));
}
Watch out. Using an operation on a generic type without declaring the trait that provides it. Add a bound like T: PartialOrd so the compiler knows the operation is available.
Functions
Functions are where Rust's biggest ideas become concrete. A signature is a list of types and something more: a contract describing who owns each value, who is merely borrowing it, and for how long. The compiler checks that contract at every call, which is why Rust functions can be both safe and fast without a garbage collector.
In this deep dive you will see how signatures express ownership, why the final expression of a body is the return value, and how borrowing and lifetimes fit together. You will also look at generics and closures, which let a single function serve many types and carry behavior around as a value.
Reading a function signature
A Rust signature tells you a great deal at a glance. A parameter like s: String means the function takes ownership. A parameter like s: &String means it borrows immutably. A parameter like s: &mut String means it borrows with permission to modify. Learning to read these three forms fluently is the key to understanding Rust functions.
The return type after the arrow follows the same rules. Returning String hands a new owned value back to the caller, while returning &str lends a view into existing data. Choosing correctly makes your functions easy to use and keeps ownership clear.
fn take(s: String) {}
fn borrow(s: &String) {}
fn borrow_mut(s: &mut String) {}
Expressions and returns
Rust is an expression-oriented language, meaning most constructs produce a value. The body of a function is a block, and the final expression of that block becomes the return value. There is no need for a trailing return in the common case, which makes functions read like calculations.
The semicolon is the important punctuation. Adding one to an expression turns it into a statement that discards the value and yields the unit type. If the declared return type is not unit, a stray semicolon on the last line produces a type mismatch that the compiler will point out precisely.
fn double(n: i32) -> i32 {
let result = n * 2;
result
}
Ownership and moves
Passing an owned value into a function moves it. The parameter becomes the new owner, and the original binding in the caller is frozen, because Rust enforces a single owner. Moves are normally cheap, transferring a few machine words rather than copying heap data.
Types that implement Copy are the exception: integers, floats, booleans, and characters are duplicated automatically, so the caller keeps using them. Strings and vectors own heap memory and are not Copy, so passing them by value genuinely transfers ownership. Borrow with a reference when you want the caller to keep the value.
fn own(v: Vec<i32>) -> usize {
v.len()
}
fn main() {
let nums = vec![1, 2, 3];
println!("{}", own(nums));
}
Immutable borrows
An immutable reference lets a function read a value it does not own. You create one with an ampersand and the compiler guarantees it stays valid only while the original value lives. Multiple readers are always allowed, because immutable borrows cannot change anything.
Borrowing avoids a move and avoids a copy, making it the default choice for large read-only arguments. A signature like fn print(s: &str) accepts string slices from strings, literals, and other sources, which is more flexible than demanding an owned String.
fn print_name(name: &str) {
println!("{}", name);
}
Mutable borrows
A mutable reference grants exclusive access to a borrowed value for a short period. The original variable must be declared mut, and the call site uses an ampersand followed by mut. While that reference exists, no other reference to the same value may be used.
This exclusivity is checked at compile time and is the mechanism behind Rust's safety guarantees. It rules out data races and prevents the common bug where two parts of a program modify the same data in an unexpected order. When the borrow ends, normal access resumes.
fn push_item(v: &mut Vec<i32>, x: i32) {
v.push(x);
}
fn main() {
let mut nums = vec![1];
push_item(&mut nums, 2);
}
Lifetimes and elision
A lifetime is the scope over which a reference remains valid. In most functions the compiler infers lifetimes using a few simple elision rules, so you rarely need to write them. The rules become visible mainly when a function returns a reference, because the compiler must know which input it is tied to.
An explicit lifetime parameter connects the inputs and output. If a function takes two references and returns one, writing all three with the same 'a tells Rust the result lives no longer than the shorter input. The compiler then rejects any call that could produce a dangling reference.
fn first<'a>(items: &'a [i32]) -> &'a i32 {
&items[0]
}
Closures as arguments
Closures are anonymous functions that can capture their environment, and they are the Rust equivalent of passing behavior into a function. They use pipes for parameters, and their types are inferred. Standard iterator adapters such as map and filter take closures, making data transformations compact and readable.
A closure usually borrows the values it captures. If you need it to own them, perhaps because you are moving the closure into a thread, use the move keyword. Every closure implements one of the Fn traits, and functions can accept them using a generic parameter with the appropriate trait bound.
fn apply<F>(f: F, x: i32) -> i32
where F: Fn(i32) -> i32 {
f(x)
}
Generic functions
Generics let you write one function that works for many types. A type parameter in angle brackets stands in for the concrete type chosen at each call. Rust generates a specialized version for every type actually used, so there is no boxing and no runtime dispatch cost.
Trait bounds tell the compiler which operations are available on the generic type. With a bound like T: PartialOrd, a function can compare two values of type T. Bounds keep generics honest: the body of the function can only use capabilities that the signature promises.
fn larger<T: PartialOrd>(a: T, b: T) -> T {
if a > b { a } else { b }
}
Function reference
These are the functions you will reach for most often. Each one is shown with its syntax, its inputs and outputs, a working example, and the mistakes to avoid.
fn
User-defined form
The fn keyword declares a function: a name, typed parameters, an optional return type, and a body. Functions are the basic unit of executable code in Rust.
| Syntax | fn add(a: i32, b: i32) -> i32 { a + b } |
|---|---|
| Parameters | a — First i32 parameter b — Second i32 parameter |
| Returns | The type after ->; here i32. Leaving it off means the unit type (). |
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
println!("{}", add(2, 3));
}
What you can do with it. Name and reuse a block of logic Structure a program into small units Define the main entry point
Choose it when. Choose fn for a named, reusable block, rather than a closure when you need a short inline helper that captures local state.
| Mistake | Fix |
|---|---|
| Expecting an implicit return like some languages | The last expression without a semicolon is returned; use return only for early exits. |
| Mismatching the body's type with the declared return type | Make the final expression produce exactly the annotated type. |
closure
User-defined form
A closure is an anonymous function you can store in a variable or pass to another function. It can capture values from the scope where it is defined.
| Syntax | let double = |x: i32| x * 2; |
|---|---|
| Parameters | x — The closure's single argument |
| Returns | The value of the body; here i32. |
fn main() {
let double = |x: i32| x * 2;
println!("{}", double(5));
}
What you can do with it. Pass a small function to an iterator adapter Write inline callbacks Capture local configuration for a helper
Choose it when. Choose a closure for a short inline function that captures its environment, rather than fn when no capture is needed.
| Mistake | Fix |
|---|---|
| Moving a captured value and then using the original | Borrow with a normal capture, or add move only when you intend to transfer ownership. |
| Passing a closure borrowing locals to a spawned thread | Use the move keyword so the closure owns what it needs for the 'static lifetime. |
generic function
User-defined form
A generic function works over many types through type parameters, with trait bounds describing what those types must support. Rust compiles a specialized version for each concrete type.
| Syntax | fn largest<T: PartialOrd + Copy>(a: T, b: T) -> T { if a > b { a } else { b } } |
|---|---|
| Parameters | T — A type parameter constrained by trait bounds |
| Returns | A value of the generic type T. |
fn largest<T: PartialOrd + Copy>(a: T, b: T) -> T {
if a > b { a } else { b }
}
What you can do with it. Write one implementation for many types Build reusable collection and algorithm code Avoid duplicating nearly identical functions
Choose it when. Choose generics for type-flexible code with no runtime cost, rather than trait objects when the concrete type varies at runtime.
| Mistake | Fix |
|---|---|
| Using an operation the bounds do not guarantee | Add the needed trait bound, such as PartialOrd, before calling that operation. |
| Over-constraining with unnecessary traits | Keep bounds minimal so more types can satisfy them. |
method
User-defined form
A method is a function defined in an impl block whose first parameter is &self, &mut self, or self. That receiver lets you call it with dot syntax on a value.
| Syntax | impl Rectangle { fn area(&self) -> u32 { self.w * self.h } } |
|---|---|
| Parameters | &self — A borrowed reference to the instance |
| Returns | Whatever the body evaluates to; here u32. |
struct Rectangle { w: u32, h: u32 }
impl Rectangle {
fn area(&self) -> u32 {
self.w * self.h
}
}
What you can do with it. Attach behavior to a struct Provide chainable builder methods Encapsulate a type's internal data
Choose it when. Choose a method when an operation naturally belongs to a type, rather than a free function that takes the value explicitly.
| Mistake | Fix |
|---|---|
| Forgetting & on self and taking ownership accidentally | Use &self for reading and &mut self for mutation; take self only when consuming. |
| Using &mut self when the method only reads | Use &self so the method works on shared, immutable references. |
associated function
User-defined form
An associated function lives in an impl block but has no self parameter. You call it on the type itself, which makes it the natural home for constructors.
| Syntax | impl Rectangle { fn new(w: u32, h: u32) -> Self { Self { w, h } } } |
|---|---|
| Parameters | w — The width value h — The height value |
| Returns | A newly built instance; here Self, meaning Rectangle. |
struct Rectangle { w: u32, h: u32 }
impl Rectangle {
fn new(w: u32, h: u32) -> Self {
Self { w, h }
}
}
What you can do with it. Define a conventional constructor Offer named alternate constructors Group type-level helpers with the type
Choose it when. Choose an associated function for constructors and type-level helpers, rather than a method when no instance exists yet.
| Mistake | Fix |
|---|---|
| Adding self by accident | Without self it is an associated function called as Type::name; with self it becomes a method. |
| Confusing Self with self | Self is the type itself; self is the receiver instance inside a method. |
println!
Macro
println! prints formatted text to standard output with a trailing newline. It is a macro, not a function, so Rust checks your format string against the arguments at compile time.
| Syntax | println!("x = {}", x); |
|---|---|
| Parameters | format — A string with {} or named placeholders args — The values to interpolate |
| Returns | Nothing; it expands to code that writes to stdout. |
fn main() {
let name = "Ana";
let n = 3;
println!("{} has {} items", name, n);
}
What you can do with it. Print debug values while learning Show program status and results Format output with width and precision
Choose it when. Choose println! for convenient formatted stdout, rather than writing to a locked stdout handle directly.
| Mistake | Fix |
|---|---|
| Passing a type that does not implement Display | Use {:?} for Debug formatting, or implement Display for your type. |
| Confusing it with print!, which has no newline | Reach for println! when you want each message on its own line. |
vec!
Macro
vec! builds a Vec from a list of elements, or from one repeated value. It is a convenience macro that expands to allocation and pushes.
| Syntax | let v = vec![1, 2, 3]; |
|---|---|
| Parameters | elements — Comma-separated values, or value ; count for repetition |
| Returns | An owned Vec<T> holding the supplied elements. |
fn main() {
let v = vec![1, 2, 3];
let zeros = vec![0; 5];
}
What you can do with it. Create a growable list in one line Initialize a buffer of repeated values Build quick test data
Choose it when. Choose vec! for a growable heap list, rather than an array when the size is fixed and known at compile time.
| Mistake | Fix |
|---|---|
| Assuming it does not allocate | vec! creates a heap-backed Vec, unlike a fixed-size array literal. |
| Using the repetition form with a non-Clone type | value ; count requires Clone; build in a loop for types that are not Clone. |
String::from
Associated function
String::from creates an owned String from a string slice, copying the text into fresh heap storage so the new value owns its data.
| Syntax | let s = String::from("hello"); |
|---|---|
| Parameters | value — A &str or other value convertible to String |
| Returns | A new owned String. |
fn main() {
let s = String::from("hello");
println!("{}!", s);
}
What you can do with it. Turn a literal into an owned string Build a value you can return from a function Store text that must outlive a borrow
Choose it when. Choose String::from when you need to own text data, rather than a borrowed &str when the text already lives long enough.
| Mistake | Fix |
|---|---|
| Creating owned Strings when a borrow would do | Use &str for read-only parameters to avoid needless allocation. |
| Expecting String::from to borrow instead of copy | It allocates a new buffer; the original slice is unchanged. |
Option::map
Method
Option::map applies a function to the value inside a Some, leaving None untouched. It transforms an optional value without unwrapping it.
| Syntax | let len = maybe.map(|s| s.len()); |
|---|---|
| Parameters | f — A closure applied to the contained value |
| Returns | Some(f(x)) when the option holds x, or None when it is empty. |
fn main() {
let maybe = Some("hello");
let len = maybe.map(|s| s.len());
println!("{:?}", len);
}
What you can do with it. Transform a value that may be absent Chain steps while keeping the None case Avoid explicit unwrap in optional pipelines
Choose it when. Choose map to change the contents of a Some, rather than and_then when your closure itself produces an Option.
| Mistake | Fix |
|---|---|
| Using map when the closure returns another Option | Use and_then, which flattens the nested Option instead of wrapping it. |
| Expecting map to supply a value for None | map never creates a Some from None; use unwrap_or or or_else for a fallback. |
Result::unwrap_or
Method
unwrap_or returns the Ok value inside a Result, or a default you provide if it is Err. It discards the error and guarantees a plain value.
| Syntax | let n = s.parse::<i32>().unwrap_or(0); |
|---|---|
| Parameters | default — The value returned when the result is an error |
| Returns | The contained Ok value, or the supplied default. |
fn main() {
let input = "42";
let n: i32 = input.parse().unwrap_or(0);
println!("{}", n);
}
What you can do with it. Provide a fallback when parsing fails Use a default configuration value Recover simply from a recoverable error
Choose it when. Choose unwrap_or when the fallback is cheap, rather than unwrap_or_else when constructing it should be lazy.
| Mistake | Fix |
|---|---|
| Swallowing an error you actually need to see | Match on the Result or use ? when the error carries important information. |
| Using an expensive default that is always computed | Use unwrap_or_else when building the default does real work. |
iter().map
Method (iterator adapter)
iter().map borrows each element of a collection and applies a closure, producing a lazy iterator of transformed values. Nothing happens until you consume it.
| Syntax | let squares = nums.iter().map(|x| x * x); |
|---|---|
| Parameters | f — A closure applied to each borrowed element |
| Returns | A lazy iterator that yields the mapped values. |
fn main() {
let nums = vec![1, 2, 3];
let squares: Vec<i32> = nums.iter().map(|x| x * x).collect();
}
What you can do with it. Transform every element of a collection Build a pipeline with filter and take Avoid an intermediate mutable vector
Choose it when. Choose iter().map for a lazy transformation you can chain, rather than a for loop when you want a composable pipeline.
| Mistake | Fix |
|---|---|
| Forgetting that the adapter is lazy | Consume it with collect, sum, or a for loop or no work is done. |
| Expecting to mutate the original elements | iter() yields references; use iter_mut() when you need to change them. |
collect
Method (iterator consumer)
collect consumes an iterator and gathers its items into a collection such as Vec, String, or HashMap. The target type is inferred from context or an explicit annotation.
| Syntax | let v: Vec<i32> = nums.iter().map(|x| x * 2).collect(); |
|---|---|
| Returns | A collection built from the iterator's items, with the type determined by the annotation. |
fn main() {
let nums = vec![1, 2, 3];
let doubled: Vec<i32> = nums.iter().map(|x| x * 2).collect();
}
What you can do with it. Turn a mapped iterator into a Vec Join characters into a String Build sets and maps from a stream of pairs
Choose it when. Choose collect when you need owned, materialized data, rather than leaving the iterator lazy until a later step.
| Mistake | Fix |
|---|---|
| Leaving the collection type ambiguous | Annotate the binding, as in let v: Vec<_> = ...collect(), so Rust knows the target. |
| Collecting an iterator of Results into a Vec | Use collect::<Result<Vec<_>, _>>() to stop at the first error instead. |
sort
Method
sort reorders a mutable slice in ascending order, in place, while keeping the relative order of equal elements. The faster sort_unstable drops that stability guarantee.
| Syntax | nums.sort(); |
|---|---|
| Returns | Nothing; the slice is reordered in place. |
fn main() {
let mut nums = vec![3, 1, 2];
nums.sort();
}
What you can do with it. Put a vector of numbers in order Sort records with sort_by or sort_by_key Prepare data for binary search
Choose it when. Choose sort for a stable in-place reorder, rather than sort_unstable when speed matters more than preserving equal order.
| Mistake | Fix |
|---|---|
| Trying to sort an immutable binding | Declare the vector with mut, because sort changes it in place. |
| Choosing sort when stability is irrelevant | Use sort_unstable for a speed boost when equal elements have no meaningful order. |
clone
Method (Clone trait)
clone makes a deep, independent copy of a value by duplicating its owned data. It comes from the Clone trait and can be surprisingly expensive for large collections.
| Syntax | let b = a.clone(); |
|---|---|
| Returns | A new owned value that is a copy of the original. |
fn main() {
let a = vec![1, 2, 3];
let b = a.clone();
println!("{:?} {:?}", a, b);
}
What you can do with it. Duplicate a Vec or String you must keep separately Produce an owned copy to return or store Satisfy an API that requires ownership
Choose it when. Choose clone when you truly need a second independent owner, rather than a reference when shared read-only access is enough.
| Mistake | Fix |
|---|---|
| Cloning when a borrow would do | Pass &T instead; borrowing costs nothing while clone copies the data. |
| Cloning large data inside a hot loop | Restructure to borrow or move, so you avoid repeated deep copies. |
Common mistakes here
| Mistake | Fix |
|---|---|
| Using a variable after its value was moved into a function | Pass a reference with & when the caller still needs the value afterward. |
| Putting a semicolon after the intended return expression | Leave off the semicolon so the final expression becomes the function's value. |
| Trying to mutate through an immutable reference | Declare the parameter as &mut T and pass &mut variable from a mut binding. |
| Returning a reference to a local variable | Return an owned value instead, since the local dies when the function returns. |
| Holding immutable and mutable borrows of the same value at once | End the first borrow before creating the second, so the accesses never overlap. |
The example, line by line
This complete Rust program defines a small helper function and calls it from main.
| Code | What it does |
|---|---|
1fn add(a: i32, b: i32) -> i32 { | Defines add with two typed i32 parameters and an i32 return type. |
2 a + b | The final expression, with no semicolon, is the value returned to the caller. |
3} | The closing brace ends the body of add. |
4fn main() { | Defines main, the entry point of every Rust binary. |
5 let sum = add(3, 4); | Calls add with two integer literals and binds the returned value to sum. |
6 println!("Sum: {}", sum); | Prints the result, with the braces acting as a placeholder for sum. |
7} | The closing brace ends main and the program. |
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let sum = add(3, 4);
println!("Sum: {}", sum);
}
Worked variations
Borrowing instead of moving
This version takes a reference so the caller keeps ownership of the string. The function borrows the String immutably to read its length, then main can still use the original value. This pattern avoids both a move and an unnecessary copy.
fn report_len(s: &String) -> usize {
s.len()
}
fn main() {
let text = String::from("hello");
let n = report_len(&text);
println!("{} {}\n", text, n);
}
A closure with an iterator
Here a closure is passed to map to transform each element. The closure captures nothing, so it borrows no local state. Iterators and closures work together naturally, letting you describe a transformation without writing an explicit loop.
fn main() {
let nums = vec![1, 2, 3];
let doubled: Vec<i32> = nums
.iter()
.map(|x| x * 2)
.collect();
println!("{:?}", doubled);
}
A generic helper with a bound
This function works for any type that can be compared with the greater-than operator. The trait bound PartialOrd is what grants the function permission to compare its arguments. Rust generates a suitable version for each concrete type you use.
fn biggest<T: PartialOrd>(a: T, b: T) -> T {
if a > b { a } else { b }
}
fn main() {
println!("{}", biggest(3, 7));
println!("{}", biggest(1.5, 0.5));
}
Common mistakes
| Mistake | Fix |
|---|---|
| Passing an owned String when a string slice would be more flexible | Prefer &str parameters for read-only text so literals and owned strings both work. |
| Fighting the borrow checker by cloning everything | Restructure with references or scopes first, and clone only when ownership is truly needed. |
| Writing lifetimes when elision would handle the function | Let the compiler infer lifetimes unless a returned reference has ambiguous origin. |
| Declaring a closure parameter with the wrong inferred type | Add explicit types like |x: i32| when inference cannot determine the parameter. |
| Using a generic type's method without declaring its trait bound | Add the trait to the signature, such as T: PartialOrd, so the method is available. |
Practice
- Write a function celsius_to_fahrenheit(c: f64) -> f64 using the final-expression return style.
- Write a function that borrows a &str and returns its length without taking ownership.
- Write a function take_and_return(s: String) -> String, then call it and reuse the result.
- Write a function with a mutable reference that appends a character to a String.
- Write a generic function first_or_default<T: Copy>(items: &[T], fallback: T) -> T.