2022-12-21 16:36:30 +01:00
|
|
|
# `String` vs `str`
|
|
|
|
|
|
|
|
We can now understand the two string types in Rust:
|
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
fn main() {
|
2023-01-24 08:52:55 +00:00
|
|
|
let s1: &str = "World";
|
2022-12-21 16:36:30 +01:00
|
|
|
println!("s1: {s1}");
|
|
|
|
|
|
|
|
let mut s2: String = String::from("Hello ");
|
|
|
|
println!("s2: {s2}");
|
|
|
|
s2.push_str(s1);
|
|
|
|
println!("s2: {s2}");
|
2023-01-24 08:52:55 +00:00
|
|
|
|
|
|
|
let s3: &str = &s2[6..];
|
|
|
|
println!("s3: {s3}");
|
2022-12-21 16:36:30 +01:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
Rust terminology:
|
|
|
|
|
|
|
|
* `&str` an immutable reference to a string slice.
|
2022-12-21 09:29:04 -08:00
|
|
|
* `String` a mutable string buffer.
|
2023-01-13 13:14:19 +00:00
|
|
|
|
|
|
|
<details>
|
|
|
|
|
2023-01-24 14:20:18 +00:00
|
|
|
* `&str` introduces 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.
|
2023-01-13 13:14:19 +00:00
|
|
|
|
2023-01-24 08:52:55 +00:00
|
|
|
* Rust’s `String` type is a wrapper around a vector of bytes. As with a `Vec<T>`, it is owned.
|
|
|
|
|
2023-01-24 14:20:18 +00:00
|
|
|
* 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 the `push()` and `push_str()` methods.
|
2023-01-13 13:14:19 +00:00
|
|
|
|
2023-01-24 14:20:18 +00:00
|
|
|
* The `format!()` macro is a convenient way to generate an owned string from dynamic values. It
|
|
|
|
accepts the same format specification as `println!()`.
|
2023-01-13 13:14:19 +00:00
|
|
|
|
2023-01-24 08:52:55 +00:00
|
|
|
* You can borrow `&str` slices from `String` via `&` and optionally range selection.
|
|
|
|
|
|
|
|
* For C++ programmers: think of `&str` as `const char*` from C++, but the one that always points
|
2023-01-24 14:20:18 +00:00
|
|
|
to a valid string in memory. Rust `String` is a rough equivalent of `std::string` from C++
|
|
|
|
(main difference: it can only contain UTF-8 encoded bytes and will never use a small-string optimization).
|
2023-01-24 08:52:55 +00:00
|
|
|
|
2023-01-13 13:14:19 +00:00
|
|
|
</details>
|