1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-01-23 22:13:02 +02:00

Update string-slices.md (#209)

* Update string-slices.md

* Adding an extra example of converting `String` back to `&str`.
* C++ who would often read this guide could get immediate intuitive understanding of Rust strings if you compare them to C++ equivalents.

* Expand on `String` vs `std::string`

Co-authored-by: Martin Geisler <martin@geisler.net>
This commit is contained in:
Igor Petruk 2023-01-24 08:52:55 +00:00 committed by GitHub
parent 4444e9a078
commit 6702accbbb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -4,13 +4,16 @@ We can now understand the two string types in Rust:
```rust,editable
fn main() {
let s1: &str = "Hello";
let s1: &str = "World";
println!("s1: {s1}");
let mut s2: String = String::from("Hello ");
println!("s2: {s2}");
s2.push_str(s1);
println!("s2: {s2}");
let s3: &str = &s2[6..];
println!("s3: {s3}");
}
```
@ -23,10 +26,17 @@ Rust terminology:
* `&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.
* Rust’s `String` type is a wrapper around a vector of bytes. As with a `Vec<T>`, it is mutable and owned.
* Rust’s `String` type is a wrapper around a vector of bytes. As with a `Vec<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 the `to_string` method.
* The `push_str` method appends a string slice to the string.
* 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
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).
</details>