Click a card to flip it · 16 terms
Rust has two main string types. This deck covers String, which owns its data and can grow, and &str, a borrowed string slice used for reading text.
A borrowed string slice, a read-only view into text.
When you only need to read text, not own or change it.
let name: &str = "Alice";
An owned, growable text type stored on the heap.
When you need to build, modify, or own text.
let s = String::from("hello");
String owns heap data and can grow. &str is a borrowed read-only view.
String when building or changing text. &str when only reading.
fn greet(name: &str) {}greet(&my_string); // both work
Appends a &str to a mutable String.
Adding multiple characters to a string you own.
let mut s = String::from("plan");s.push_str("_pro");
Appends a single char to a mutable String.
Adding exactly one character.
s.push('!');
Converts a String to a &str, borrows without moving.
When a function expects &str but you have a String.
s.as_str()// or just: &s
Converts a &str to an owned String.
When you need to own a copy of a string literal.
"basic".to_string()
Returns an iterator over the Unicode characters in a string.
Safe way to loop over characters, do not index strings directly.
for c in s.chars() { println!("{}", c);}
A reference to a String is automatically converted to &str by the compiler.
Functions taking &str also accept &String. Rust handles it silently.
fn greet(s: &str) {}greet(&my_string); // auto-coerced
Borrows a String as a byte slice. The original string stays valid.
When you need to inspect bytes without consuming the string.
let bytes = s.as_bytes();// s is still valid
Consumes a String and converts it to a Vec<u8>. The original is gone.
When you need raw bytes and will no longer use the string.
let bytes = s.into_bytes();// s is gone now
A string slice that lives for the entire program lifetime. String literals are this type.
The default type of any string literal in your code.
let s: &'static str = "hello";// baked into the binary
The encoding Rust uses to store all strings. Each character can take 1 to 4 bytes.
Why you cannot index strings by position. Use .chars() to get characters safely.
// s[2] won't compiles.chars().nth(2); // correct
A String holds three parts: a pointer to heap data, a length, and a capacity.
Explains why String can grow. If capacity fills up, Rust reallocates a larger block.
ptr | len | cap
Converts a Vec<u8> to a String. Returns a Result because bytes might not be valid UTF-8.
When you have raw bytes and need a string.
String::from_utf8(bytes) .unwrap()
A borrowed view into part of a String. Does not copy the data.
When you need a substring without taking ownership.
let hello = &s[0..5];// end index is excluded