UTF-8
String collection
Use .push and .push_str to append to a string.
Example:
Ā Ā // opt 1
Ā Ā let _s = "whatever".to_string();
Ā Ā // opt 2
Ā Ā let _s = String::from("whatever");
Ā Ā // opt 3
Ā Ā let mut _s = String::from("foo");
Ā Ā _s.push_str("bar");
Ā Ā _s.push('!');
Ā Ā println!("{}", _s);
Ā Ā // Output: foobar!
Ā Ā
Ā Ā
Use the + operator to concatenate string values.
Ā Ā let s1 = String::from("Hello, ");
Ā Ā let s2 = String::from("world");
Ā Ā let s3 = s1 + &s2; // s1 has been moved here and can no longer be used
Ā Ā println!("s3 is {}", s3);
With format!
Ā Ā let hi1 = String::from("Shalom");
Ā Ā let hi2 = String::from("Hola");
Ā Ā let full_message = format!("{hi1} - {hi2}");
Ā Ā println!("{full_message}");
Ā Ā // Output: Shalom - Hola
From the Rust book:
"If we need to concatenate multiple strings, the behavior of theĀ +Ā operator gets unwieldy:
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = s1 + "-" + &s2 + "-" + &s3;
At this point,Ā sĀ will beĀ tic-tac-toe. With all of theĀ +Ā andĀ "Ā characters, itās difficult to see whatās going on. For combining strings in more complicated ways, we can instead use theĀ format!Ā macro:
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = format!("{s1}-{s2}-{s3}");
This code also setsĀ sĀ toĀ tic-tac-toe. TheĀ format!Ā macro works likeĀ println!, but instead of printing the output to the screen, it returns aĀ StringĀ with the contents. The version of the code usingĀ format!Ā is much easier to read, and the code generated by theĀ format!Ā macro uses references so that this call doesnāt take ownership of any of its parameters."