Rust Strings
Text in Rust comes in two main flavours, and knowing the difference saves a lot of confusion:
| Type | What it is | Owned? | Can grow? | Example |
|---|---|---|---|---|
&str |
a string slice: a borrowed view of some UTF-8 text | no | no | "hello" |
String |
a heap-allocated, growable UTF-8 string | yes | yes | String::from("hello") |
A string literal written in quotes, like "hello", is a &str that is baked into your program. A String is a buffer you own and can change at runtime — think of it as a Vec of bytes that is guaranteed to hold valid text.
Creating strings
fn main() {
let literal: &str = "Rust"; // string slice
let a = String::from("Hello"); // String from a literal
let b = "World".to_string(); // another way
let c = String::new(); // empty String
println!("{} / {} / {} / '{}'", literal, a, b, c);
println!("Is c empty? {}", c.is_empty());
}Rust / Hello / World / ''
Is c empty? true
String::from(...) and .to_string() do the same job — use whichever reads better to you.
Changing a String
A String declared with let mut can be modified. push_str appends a slice, push appends a single char.
fn main() {
let mut shopping = String::from("Shopping:");
shopping.push_str(" apples");
shopping.push(',');
shopping.push_str(" bread");
println!("{}", shopping);
println!("Length in bytes: {}", shopping.len());
shopping.clear();
println!("After clear: '{}' (len {})", shopping, shopping.len());
}Shopping: apples, bread
Length in bytes: 23
After clear: '' (len 0)
Joining strings
There are several ways to combine text:
fn main() {
let first = String::from("Ada");
let last = String::from("Lovelace");
// 1. format! builds a new String and leaves the originals untouched
let full = format!("{} {}", first, last);
println!("format!: {}", full);
// 2. The + operator takes ownership of the left side
let greeting = String::from("Hi, ") + &first + "!";
println!("+ : {}", greeting);
// 3. Joining a list of pieces
let words = ["red", "green", "blue"];
println!("join : {}", words.join(", "));
}format!: Ada Lovelace
+ : Hi, Ada!
join : red, green, blue
Tip:
format!is usually the clearest choice. It works likeprintln!, but returns the text as aStringinstead of printing it.
The + operator has a quirk: the left side must be an owned String (it is moved into the result), and the right side must be a &str, which is why we write &first.
Useful methods
| Method | Does | Example result |
|---|---|---|
len() |
number of bytes | "héllo".len() → 6 |
chars().count() |
number of characters | "héllo".chars().count() → 5 |
to_uppercase() / to_lowercase() |
change case | "Hi".to_uppercase() → "HI" |
trim() |
remove surrounding whitespace | " x ".trim() → "x" |
contains(p) |
does it contain p? |
"rustacean".contains("rust") → true |
replace(a, b) |
replace all a with b |
"a-b".replace("-", "+") → "a+b" |
split(sep) |
iterate over parts | "a,b".split(',') → "a", "b" |
ends_with(p) |
suffix check | "main.rs".ends_with(".rs") → true |
fn main() {
let raw = " The quick brown fox ";
let text = raw.trim();
println!("Trimmed : '{}'", text);
println!("Upper : {}", text.to_uppercase());
println!("Has fox?: {}", text.contains("fox"));
println!("Replaced: {}", text.replace("quick", "lazy"));
for (i, word) in text.split(' ').enumerate() {
println!("word {}: {}", i, word);
}
}Trimmed : 'The quick brown fox'
Upper : THE QUICK BROWN FOX
Has fox?: true
Replaced: The lazy brown fox
word 0: The
word 1: quick
word 2: brown
word 3: fox
Characters, bytes and indexing
Rust strings are UTF-8, so a single character can take 1 to 4 bytes. Because of this, you cannot index a string with s[0] — Rust refuses to guess whether you want a byte or a character. Instead, iterate with .chars(), or take a slice by byte range when you know it is safe.
fn main() {
let word = "naïve";
println!("Bytes: {}, chars: {}", word.len(), word.chars().count());
for c in word.chars() {
print!("[{}]", c);
}
println!();
let first_char = word.chars().next().unwrap();
println!("First char: {}", first_char);
let reversed: String = word.chars().rev().collect();
println!("Reversed: {}", reversed);
let prefix = &word[0..2]; // bytes 0 and 1 are "na"
println!("Slice: {}", prefix);
}Bytes: 6, chars: 5
[n][a][ï][v][e]
First char: n
Reversed: evïan
Slice: na
Note: A byte-range slice like
&word[0..3]would cutïin half and panic at runtime. Slice only on character boundaries, or work with.chars().
&str or String in function parameters?
If a function only needs to read text, take a &str. You can pass both literals and Strings (using &my_string) to it, which makes the function more flexible. Take a String only when the function needs to own or keep the text.
Test yourself
Which type is a growable, owned string?
&strStringcharstr[]
What does "héllo".len() return?
- 5
- 6
- 4
- It does not compile
Why does let c = s[0]; not compile for a String s?
- Strings are immutable
- Indexing could split a multi-byte UTF-8 character, so Rust forbids it
- You must write
s(0) - Strings start at index 1