Rust

Lesson 01

Ownership and borrowing

Use borrowed inputs when a function only reads data, so callers keep ownership of their values.

Good Code

src/review_title.rs
pub fn normalize_title(title: &str) -> String {
    // Borrowing says this function reads the title without consuming it.
    title.trim().replace(char::is_whitespace, " ")
}

Bad Code

review_title.rs
pub fn normalize_title(title: String) -> String {
    // Taking String forces callers to give up ownership for a read-only task.
    title.trim().replace(char::is_whitespace, " ")
}

Review Notes

What to review

Good Code

The good version accepts &str, which works with String, string slices, and literals without moving the caller's value. The function creates a new normalized value only for the returned title.

Bad Code

The bad version takes String even though it only reads the input. Callers lose ownership and may clone strings just to keep using the title after the call.

Takeaways

  • A Rust function should take ownership only when it stores, transforms, or consumes the value.