Iniciante Fundamentos
Strings
Rust tem dois tipos principais de texto: String, que pode crescer e é dona dos dados, e &str, uma referência a um texto (fatia de string).
String vs &str
fn main() {
let fixo: &str = "texto fixo"; // literal, imutável
let mut dinamico = String::from("Olá"); // String, pode crescer
dinamico.push_str(", mundo");
println!("{} | {}", fixo, dinamico);
}
Concatenação
Você pode usar + ou push_str, ou ainda a macro format!:
fn main() {
let a = String::from("bom");
let b = String::from(" dia");
let junto = a + &b; // 'a' é movida aqui
println!("{}", junto);
let nome = "Ana";
let msg = format!("Olá, {}!", nome);
println!("{}", msg);
}
Métodos úteis
fn main() {
let texto = String::from("Rust é legal");
println!("{}", texto.len()); // tamanho em bytes
println!("{}", texto.to_uppercase()); // MAIÚSCULAS
println!("{}", texto.contains("legal")); // true
println!("{}", texto.replace("legal", "ótimo"));
}
De &str para String
fn main() {
let s1 = "texto".to_string();
let s2 = String::from("texto");
println!("{} {}", s1, s2);
}