mirror of
https://github.com/sunface/rust-by-practice.git
synced 2025-06-23 12:39:42 +00:00
update string.md
This commit is contained in:
@ -136,4 +136,32 @@ fn main() {
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
7.
|
||||
```rust
|
||||
use std::mem;
|
||||
|
||||
fn main() {
|
||||
let story = String::from("Rust By Practice");
|
||||
|
||||
// Prevent automatically dropping the String's data
|
||||
let mut story = mem::ManuallyDrop::new(story);
|
||||
|
||||
let ptr = story.as_mut_ptr();
|
||||
let len = story.len();
|
||||
let capacity = story.capacity();
|
||||
|
||||
// story has nineteen bytes
|
||||
assert_eq!(16, len);
|
||||
|
||||
// We can re-build a String out of ptr, len, and capacity. This is all
|
||||
// unsafe because we are responsible for making sure the components are
|
||||
// valid:
|
||||
let s = unsafe { String::from_raw_parts(ptr, len, capacity) };
|
||||
|
||||
assert_eq!(*story, s);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
Reference in New Issue
Block a user