Rust has two primary string types, each serving different purposes.
String vs &str
String
Owned, growable, heap-allocated text
Mutable by default (if declared mut)
Created with String::from() or .to_string()
&str
Borrowed string slice
Fixed size, immutable
String literals are &str
: = ::(\
let
s1
String
String
from
"hello\"); // Owned
let s2: &str = \"world\"; // Borrowed (literal)
let s3: &str = &s1[..]; // Slice of String
Working with Strings
fnmain() {
letmut s = String::from(\"Hello\");
// Append string
s.push_str(\", \");
// Push single character
s.push('W');
// Concatenation with +
let s2 = s + \"orld\"; // \"Hello, World\"
// Format macro
let s3 = format!(\"{}, {}\", s2, \"Rust\");
}
lets = \"hello\";
// Bytes
for b in s.as_bytes() {
println!(\"Byte: {}\", b);
}
// Characters (handles Unicode)
for c in s.chars() {
println!(\"Char: {}\", c);
}