C9: std::String Flashcards
std::String
The String type, which is provided by Rust’s standard library rather than coded into the core language, is a growable, mutable, owned, UTF-8 encoded string type
Creating a New String
let mut s = String::new();
Using the to_string method to create a String from a string literal
let data = “initial contents”;
let s = data.to_string(); // the method also works on a literal directly: let s = "initial contents".to_string();
Using the String::from function to create a String from a string literal
let s = String::from(“initial contents”);
Updating a String
let mut s1 = String::from(“foo”);
let s2 = “bar”;
s1.push_str(s2);
println!(“s2 is {s2}”);
Concatenation with the + Operator
let s1 = String::from(“tic”);
let s2 = String::from(“tac”);
let s3 = String::from(“toe”);
let s = s1 + "-" + &s2 + "-" + &s3;
Concatenation with the format! Macro
let s = format!(“{s1}-{s2}-{s3}”);
Does this work?
let s1 = String::from("hello"); let h = s1[0];
NO:
$ cargo run
Compiling collections v0.1.0 (file:///projects/collections)
error[E0277]: the type String
cannot be indexed by {integer}
–> src/main.rs:3:13
|
3 | let h = s1[0];
| ^^^^^ String
cannot be indexed by {integer}
|
= help: the trait Index<{integer}>
is not implemented for String
= help: the following other types implement trait Index<Idx>
:
<String as Index<RangeFrom<usize>>>
<String as Index<RangeFull>>
<String as Index<RangeInclusive<usize>>>
<String as Index<RangeTo<usize>>>
<String as Index<RangeToInclusive<usize>>>
<String as Index<std::ops::Range<usize>>>
<str as Index<i>></i></usize></usize></usize></usize></RangeFull></usize>
For more information about this error, try rustc --explain E0277
.
error: could not compile collections
due to previous error
Does this work?
let hello = “Здравствуйте”;
let answer = &hello[0];
NO
Does this work?
let hello = “Здравствуйте”;
let s = &hello[0..4];
YES. Slicing Strings
Methods for Iterating Over Strings
for c in “Зд”.chars() {
println!(“{c}”);
}
for b in “Зд”.bytes() {
println!(“{b}”);
}
What is s?
let hello = “Здравствуйте”;
let s = &hello[0..4];
s = “Зд”
Here, s will be a &str that contains the first 4 bytes of the string. Earlier, we mentioned that each of these characters was 2 bytes, which means s will be Зд.