Strings
We can now understand the two string types in Rust:
&stris a slice of UTF-8 encoded bytes, similar to&[u8].Stringis an owned buffer of UTF-8 encoded bytes, similar toVec<T>.
1. ```
fn main() {
```
2. ```
let s1: &str = "World";
```
3. ```
println!("s1: {s1}");
```
5. ```
let mut s2: String = String::from("Hello ");
```
6. ```
println!("s2: {s2}");
```
7. ```
s2.push_str(s1);
```
8. ```
println!("s2: {s2}");
```
10. ```
let s3: &str = &s2[s2.len() - s1.len()..];
```
11. ```
println!("s3: {s3}");
```
12. ```
}
```
This slide should take about 10 minutes.
&strintroduces a string slice, which is an immutable reference to UTF-8 encoded string data stored in a block of memory. String literals ("Hello"), are stored in the program’s binary.- Rust’s
Stringtype is a wrapper around a vector of bytes. As with aVec<T>, it is owned. - As with many other types
String::from()creates a string from a string literal;String::new()creates a new empty string, to which string data can be added using thepush()andpush_str()methods. - The
format!()macro is a convenient way to generate an owned string from dynamic values. It accepts the same format specification asprintln!(). - You can borrow
&strslices fromStringvia&and optionally range selection. If you select a byte range that is not aligned to character boundaries, the expression will panic. Thecharsiterator iterates over characters and is preferred over trying to get character boundaries right. - For C++ programmers: think of
&strasstd::string_viewfrom C++, but the one that always points to a valid string in memory. RustStringis a rough equivalent ofstd::stringfrom C++ (main difference: it can only contain UTF-8 encoded bytes and will never use a small-string optimization). - Byte strings literals allow you to create a
&[u8]value directly:
1.
fn main() {
2.
println!("{:?}", b"abc");
3.
println!("{:?}", &[97, 98, 99]);
4.
}
- Raw strings allow you to create a &str value with escapes disabled: r"\n" == "\\n". You can embed double-quotes by using an equal amount of # on either side of the quotes:
1.
fn main() {
2.
println!(r#"<a href="link.html">link</a>"#);
3.
println!("<a href=\"link.html\">link</a>");
4.
}
