Alex Garella
18th March 2023
In Rust, there are two main string types: String
and str
.
The primary differences between them are in ownership, mutability, and how they are stored in memory.
Vec<u8>
under the hood, so it can be resized.Code example
fn main() {
let mut s = String::from("Hello"); // Create a new String with content "Hello"
s.push_str(", world!"); // Append the string ", world!" to the original String
println!("{}", s); // Output: "Hello, world!"
}
Code example
fn main() {
let s: &str = "Hello"; // Create a new &str with content "Hello"
// The following line would produce a compile-time error since &str is immutable:
// s.push_str(", world!");
println!("{}", s); // Output: "Hello"
}
Here is a code example of how to convert between String
and &str
fn main() {
let s = String::from("Hello"); // Create a new String with content "Hello"
let s_slice: &str = &s; // Create a &str slice that borrows from the String
println!("String: {}", s); // Output: "Hello"
println!("&str: {}", s_slice); // Output: "Hello"
}
String
when you need a mutable, growable string.str
(usually in its borrowed form, &str
) when you need an immutable, fixed-length string.