Strings are a fundamental data type in Rust, used for storing and manipulating text. Rust provides two main string types: String
and &str
.
String
is a growable, mutable, owned UTF-8 encoded string type. It's heap-allocated and can be modified.
&str
is an immutable string slice, often used for string literals or views into String
s. It's a reference to UTF-8 encoded string data.
Here are some ways to create strings in Rust:
// Creating a String
let mut s = String::new();
let s = String::from("Hello, Rust!");
let s = "Hello, Rust!".to_string();
// Creating a string slice
let s: &str = "Hello, Rust!";
You can concatenate strings using the +
operator or the format!
macro:
let s1 = String::from("Hello, ");
let s2 = String::from("Rust!");
let s3 = s1 + &s2; // Note: s1 is moved here and can no longer be used
// Using format! macro
let s = format!("{} {}", "Hello,", "Rust!");
You can create slices of strings using range notation:
let s = String::from("Hello, Rust!");
let slice = &s[0..5]; // "Hello"
Note: Be careful when slicing strings, as Rust strings are UTF-8 encoded. Slicing at invalid UTF-8 character boundaries will cause a runtime panic.
Rust provides various methods for working with strings:
len()
: Returns the length of the string in bytesis_empty()
: Checks if the string is emptycontains()
: Checks if the string contains a substringreplace()
: Replaces all occurrences of a patternto_lowercase()
and to_uppercase()
: Convert caseRust strings are UTF-8 encoded, providing full Unicode support. This allows for efficient storage and manipulation of international text.
When working with Unicode, be aware of the difference between characters and bytes:
let s = "नमस्ते"; // Hindi word
println!("Length in bytes: {}", s.len()); // 18
println!("Length in characters: {}", s.chars().count()); // 6
String
when you need to own and modify the string data.&str
for string literals and when you only need to read the string data.format!
macro for complex string formatting.Understanding Rust's string types and their operations is crucial for effective text manipulation in your Rust programs. For more advanced string handling, consider exploring the Rust Standard Library documentation.