Strings and Slices
UTF-8 text with owned String and borrowed str slices. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Busca en todas las páginas de la documentación
UTF-8 text with owned String and borrowed str slices. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
String owns UTF-8 bytes; &str borrows them.
let owned = String::from("hi");
let borrowed: &str = &owned;
borrowed.len() // 2Build owned strings without println.
format!("{}-{}", "a", 1) // "a-1"Split and collect parts.
let v: Vec<_> = "a,b,c".split(',').collect();
v // ["a", "b", "c"]Iterate Unicode scalar values, not bytes.
"é".chars().count() // 1
"é".len() // 2 bytes in UTF-8Parse from strings; format into strings.
"42".parse::<i32>().unwrap() // 42
42.to_string() // "42"Grow a String in place.
let mut s = String::from("a");
s.push_str("b");
s.push('!');
s // "ab!"Search helpers on str.
"hello".contains("ell") // true
"hello".starts_with("he") // trueWhitespace and line iteration.
" x\n".trim() // "x"
"a\nb".lines().next() // Some("a")Create a new string with replacements.
"a_b_a".replace('a', "x") // "x_b_x"Indexing by byte can panic mid-char - prefer chars/get.
"hi".get(0..1) // Some("h")Validate bytes as UTF-8.
String::from_utf8(vec![104, 105]).unwrap() // "hi"Clone-on-write borrowed or owned text.
use std::borrow::Cow;
let c: Cow<str> = "x".into();
c // "x"Join string slices.
["a", "b"].join("/") // "a/b"Match string prefixes with patterns.
match "https://x" {
s if s.starts_with("https://") => "secure",
_ => "other",
} // "secure"Preallocate to reduce reallocs.
let mut s = String::with_capacity(8);
s.push_str("abcd");
s.capacity() >= 8 // trueStack versions: Rust 1.97.0 · edition 2024 · Tokio 1.x · serde 1.0
Revisado por Chris St. John·Última actualización: 19 jul 2026