Rust Strings Tutorial | String vs &str - Owned and Borrowed Types Explained
Video: Rust Strings Tutorial | String vs &str - Owned and Borrowed Types Explained by Taught by Celeste AI - AI Coding Coach
Watch full page →Rust Strings Tutorial | String vs &str - Owned and Borrowed Types Explained
In Rust, strings come in two main types: the owned, growable String and the borrowed string slice &str. Understanding the difference between these types is crucial for effective memory management and string manipulation in Rust programs.
Code
fn main() {
// Owned String allocated on the heap
let greeting = String::from("Hello, World!");
println!("Greeting: {}", greeting);
// Borrowed string slice (&str) pointing to string data
let name: &str = "Rust";
println!("Language: {}", name);
// Creating an empty mutable String and appending text
let mut message = String::new();
message.push_str("Learning ");
message.push_str("Rust!");
println!("Message: {}", message);
// Using common String methods
let text = String::from("Hello Rust");
println!("Length: {}", text.len()); // Length of string in bytes
println!("Contains 'Rust': {}", text.contains("Rust")); // Check substring presence
println!("Replaced: {}", text.replace("Rust", "World")); // Replace substring
// String concatenation examples
let s1 = String::from("Hello, ");
let s2 = "Rustaceans!";
// Using + operator (moves s1)
let s3 = s1 + s2;
println!("Concatenated with +: {}", s3);
// Using format! macro (does not take ownership)
let s4 = String::from("Goodbye, ");
let s5 = "world!";
let s6 = format!("{}{}", s4, s5);
println!("Concatenated with format!: {}", s6);
// Adding single character with push()
let mut s7 = String::from("Hi");
s7.push('!');
println!("After push: {}", s7);
}
Key Points
Stringis an owned, growable string stored on the heap, while&stris a borrowed string slice referencing existing data.- Use
String::from()to create owned strings andString::new()to create empty mutable strings. - Common string methods include
len(),contains(), andreplace()for inspecting and modifying strings. - String concatenation can be done with the
+operator (which moves ownership), theformat!macro (which is flexible and non-destructive),push_str(), andpush()for single characters. - Understanding ownership and borrowing with strings is key to writing safe and efficient Rust code.