Beginner Fundamentals
Strings
Rust has two main string types. A String is an owned, growable string stored on the heap. A &str (string slice) is a borrowed view into string data, often a literal.
String vs &str
fn main() {
let literal: &str = "I am a string slice";
let owned: String = String::from("I am an owned String");
println!("{}", literal);
println!("{}", owned);
}
String literals in your code are always &str. Use String when you need to build or modify text at runtime.
Concatenation
fn main() {
let mut greeting = String::from("Hello");
greeting.push_str(", world"); // append a &str
greeting.push('!'); // append a single char
println!("{}", greeting);
let a = String::from("foo");
let b = String::from("bar");
let combined = a + &b; // a is moved, b is borrowed
println!("{}", combined);
}
Common methods
fn main() {
let text = String::from("Rust");
println!("{}", text.len()); // 4 (bytes)
println!("{}", text.is_empty()); // false
println!("{}", text.to_uppercase()); // RUST
println!("{}", text.contains("us")); // true
}
The format! macro builds a String without moving its inputs, which is often cleaner than chaining +.