Strings
Recipe | Crates |
---|---|
String | |
Placeholders | |
Concatenate strings |
[strings.incl: review (P1)](https://github.com/john-cd/rust_howto/issues/629)
String
fn main() { // `String` is Unicode, not ASCII let mut s1 = String::from("hello"); s1.push_str(", world!"); // `String` can be mutated s1.clear(); // Empties the String, making it equal to "" // Alternative initialization from string literals // `to_string` is available on any type that implements // the Display trait let s2 = "initial contents".to_string(); // Concatenation: note s1 has been moved here and can no longer // be used afterwards let s3 = s1 + &s2; // ERROR let s = format!("{s1}-{s2}-{s3}"); // String slice - contains the first 4 bytes of the string. let _s: &str = &s3[0..4]; // Caution: If we were to try to slice only part of a unicode // character’s bytes, Rust would panic at runtime. // Iteration for c in "Зд".chars() { println!("{c}"); } for b in "Зд".bytes() { println!("{b}"); } }
Placeholders
fn main() { let x = 5; let y = 10; println!("x = {x} and y + 2 = {}", y + 2); }
Use {:?}
to use the std::fmt::Debug
⮳ output format (annotate type with #[derive(Debug)]
) or {:#?}
for pretty print.
Also use dbg!(&rect1);
for debug output (returns ownership of the expression’s value).
Concatenate strings
Here are several common methods to concatenate Strings:
#[macro_use(concat_string)] extern crate concat_string; #[macro_use(concat_strs)] extern crate concat_strs; static DATE: &str = "2024-01-15"; static T: &str = "T"; static TIME: &str = "12:00:09Z"; fn main() { let _datetime = &[DATE, T, TIME].concat(); let _datetime = &[DATE, TIME].join(T); let _datetime = &[DATE, T, TIME].join(""); let _datetime = &[DATE, T, TIME].join(""); let list = [DATE, T, TIME]; // let _datetime: String = list.iter().map(|x| *x).collect(); let _datetime: String = list.iter().copied().collect(); let list = vec![DATE, T, TIME]; // let _datetime: String = list.iter().map(|x| *x).collect(); let _datetime: String = list.iter().copied().collect(); let _datetime = &format!("{}{}{}", DATE, T, TIME); let _datetime = &format!("{DATE}{T}{TIME}"); let mut datetime = String::new(); datetime.push_str(DATE); datetime.push_str(T); datetime.push_str(TIME); let mut datetime = Vec::<String>::new(); datetime.push(String::from(DATE)); datetime.push(String::from(T)); datetime.push(String::from(TIME)); let _datetime = datetime.join(""); let mut datetime = String::with_capacity(20); datetime.push_str(DATE); datetime.push_str(T); // or 'T' datetime.push_str(TIME); let _datetime = &(String::from(DATE) + &String::from(T) + &String::from(TIME)); let _datetime = &(String::from(DATE) + T + TIME); let _datetime = &(DATE.to_owned() + T + TIME); let _datetime = &(DATE.to_string() + T + TIME); let _datetime = concat_string!(DATE, T, TIME); let datetime = &concat_strs!(DATE, T, TIME); println!("{}", datetime); }
Examples from concatenation_benchmarks-rs⮳
[strings: review (P1)](https://github.com/john-cd/rust_howto/issues/630)