1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-06-16 22:27:34 +02:00

Add “More to Explore” sections (#1369)

From a discussion in #1313.
This commit is contained in:
Martin Geisler
2023-10-16 15:42:07 +02:00
committed by GitHub
parent 29c121cb54
commit f94daaea73
3 changed files with 39 additions and 14 deletions

View File

@ -29,22 +29,25 @@ fn main() {
* If students ask about it, you can mention that the underlying memory is heap allocated using the [System Allocator] and custom allocators can be implemented using the [Allocator API]
* We can inspect the memory layout with `unsafe` code. However, you should point out that this is rightfully unsafe!
## More to Explore
```rust,editable
fn main() {
let mut s1 = String::from("Hello");
s1.push(' ');
s1.push_str("world");
// DON'T DO THIS AT HOME! For educational purposes only.
// String provides no guarantees about its layout, so this could lead to
// undefined behavior.
unsafe {
let (ptr, capacity, len): (usize, usize, usize) = std::mem::transmute(s1);
println!("ptr = {ptr:#x}, len = {len}, capacity = {capacity}");
}
We can inspect the memory layout with `unsafe` Rust. However, you should point
out that this is rightfully unsafe!
```rust,editable
fn main() {
let mut s1 = String::from("Hello");
s1.push(' ');
s1.push_str("world");
// DON'T DO THIS AT HOME! For educational purposes only.
// String provides no guarantees about its layout, so this could lead to
// undefined behavior.
unsafe {
let (ptr, capacity, len): (usize, usize, usize) = std::mem::transmute(s1);
println!("ptr = {ptr:#x}, len = {len}, capacity = {capacity}");
}
```
}
```
</details>