← SEARCHABLE ARCHIVE
Rust · 2026-07-23

Rust from Basics to Mastery — Part 3

Connecting ownership, borrowing, and slices with code

INTERACTIVE READING MODE →

The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.

Ownership in Rust is a rule that determines at compile time who cleans up memory. Indicate in the function type whether the value will be moved, read-only, or mutable.

move value

fn print_name(name: String) {
    println!("{name}");
}

let player_name = String::from("Rose");
print_name(player_name);
//player_name cannot be used again here.

String owns heap data, so ownership moves when assigning or passing values. To keep the original valid, you must explicitly copy or reference it.

Immutable and Mutable References

fn print_name(name: &str) {
    println!("{name}");
}

fn add_suffix(name: &mut String) {
    name.push_str("_01");
}

let mut player_name = String::from("Rose");
print_name(&player_name);
add_suffix(&mut player_name);

&str is borrowed briefly to read the string contents, and &mut String is borrowed to change the value. You cannot use one mutable reference and another reference in the same scope at the same time.

This restriction prevents situations where values ​​change while being read or are modified in two places simultaneously.

sliced

fn first_word(text: &str) -> &str {
    match text.find(' ') {
        Some(index) => &text[..index],
        None => text,
    }
}

A slice is a reference to a contiguous portion of a string or array without owning it. Functions that do not require the entire String can use both string literals and String slices by receiving &str.

Lifetime of a Reference

The compiler ensures that the reference does not outlive the original. If you try to return a reference to a local variable outside of a function, it will not compile because the original disappears first.

When encountering an ownership error, you should first decide who the actual owner of the value should be rather than just clone it first. Borrowing is a technique to avoid copying and at the same time a contract that limits access rights to type.