Rust Strings
Working with text data in Rust
📝 What are Rust Strings?
Rust strings are collections of UTF-8 encoded text data. Rust has two main string types: string literals (&str) and owned strings (String), each serving different purposes in memory management and text manipulation.
// String literal (immutable)
let greeting = "Hello, World!";
// Owned String (mutable)
let mut name = String::from("Rust");
name.push_str(" Programming");
Output:
greeting: "Hello, World!"
name: "Rust Programming"
String Types in Rust
&str (String Slice)
Immutable reference to string data
let text: &str = "Hello";
String
Owned, growable string type
let text = String::from("Hello");
Conversion
Convert between string types
let s = "hello".to_string();
Concatenation
Combine strings together
let result = format!("{} {}", a, b);
🔹 Creating Strings
Different ways to create strings in Rust:
fn main() {
// String literals
let literal = "Hello, World!";
// Creating String from literal
let owned1 = String::from("Hello");
let owned2 = "Hello".to_string();
let owned3 = "Hello".to_owned();
// Empty string
let mut empty = String::new();
empty.push_str("Now I have content!");
println!("{}", literal);
println!("{}", owned1);
println!("{}", empty);
}
Output:
Hello, World!
Hello
Now I have content!
🔹 String Operations
Common operations you can perform on strings:
fn main() {
let mut greeting = String::from("Hello");
// Adding to strings
greeting.push(' '); // Add single character
greeting.push_str("World"); // Add string slice
// String length
println!("Length: {}", greeting.len());
// Check if empty
println!("Is empty: {}", greeting.is_empty());
// Contains substring
println!("Contains 'World': {}", greeting.contains("World"));
// Replace text
let new_greeting = greeting.replace("World", "Rust");
println!("{}", new_greeting);
}
Output:
Length: 11
Is empty: false
Contains 'World': true
Hello Rust
🔹 String Formatting
Use the format! macro to create formatted strings:
fn main() {
let name = "Alice";
let age = 30;
// Basic formatting
let intro = format!("My name is {}", name);
// Multiple values
let info = format!("Name: {}, Age: {}", name, age);
// Positional arguments
let message = format!("{0} is {1} years old. {0} likes Rust!", name, age);
// Named arguments
let formatted = format!("{name} is {age} years old", name=name, age=age);
println!("{}", intro);
println!("{}", info);
println!("{}", message);
println!("{}", formatted);
}
Output:
My name is Alice
Name: Alice, Age: 30
Alice is 30 years old. Alice likes Rust!
Alice is 30 years old