An In-Depth Guide to Rust String Types
Summary of Rust Strings
The Rust documentation on strings provides a comprehensive overview of working with string types in Rust, focusing primarily on String
and &str
. Below is a structured summary of the key concepts.
Key Concepts
String Types
- String:
- A growable, heap-allocated string type.
- Owned, meaning it manages its own memory.
- Mutable, allowing modifications (e.g., appending).
- &str:
- A string slice, which is a reference to a string.
- Immutable, meaning it cannot be changed.
- Often used to view parts of a
String
or string literals.
Creating Strings
You can create a String
using:
let mut s = String::new(); // New empty String
let s = String::from("Hello, world!"); // From a string literal
A string slice can be created via:
let s: &str = "Hello, world!"; // String literal
Modifying Strings
You can modify a String
using methods like push
, push_str
, and insert
:
let mut s = String::from("Hello");
s.push('!'); // Adds a character
s.push_str(" World"); // Adds a string slice
String Slices
A &str
can be obtained from a String
by referencing it:
let s = String::from("Hello");
let slice: &str = &s; // Borrowing the string
String Length
You can check the length of a string using the len
method:
let s = String::from("Hello");
println!("Length: {}", s.len()); // Outputs: Length: 5
Iterating Over Characters
You can iterate through characters in a String
:
for c in "नमस्ते".chars() {
println!("{}", c); // Iterates over each character
}
String Formatting
The format!
macro allows you to create formatted strings:
let name = "Alice";
let greeting = format!("Hello, {}!", name);
Conclusion
Rust provides powerful and flexible string handling features through its String
and &str
types. Understanding the distinction between owned and borrowed strings is essential for effective memory management in Rust.