Working with Text
7 min · Rust
Join strings, measure them, and change case with String methods.
Enemy 1 of 5
Rust actually has two closely related string types, which is one of the first genuinely Rust-specific things you'll run into. A string literal like "hello" is a &str (pronounced "string slice") — a fixed, read-only view into some text. A String is an owned, growable string that lives on the heap and that you can build up or modify at runtime. Most of the time you can treat them similarly, but the distinction becomes important once you start joining and modifying text.
To join two pieces of text with +, the left-hand side needs to be an owned String, not a plain &str — which is why the example below calls .to_string() on greeting before adding name to it. This is a common early stumbling block: writing "Hello, " + name without the conversion gives a compiler error, because Rust won't silently combine a borrowed slice and an owned string without you asking for it explicitly. Being explicit here is the price Rust asks in exchange for guaranteeing there's never a dangling or invalid string at runtime.
The & symbol you'll see throughout Rust code means borrowing — using a value without taking ownership of it. It's one of Rust's signature ideas and one you'll get comfortable with gradually; for now, just recognize that &str means "a borrowed view of string data."
Loading editor...