这里有人能帮我解释一下这个问题吗?谢谢了
let ptr = story.as_mut_ptr();
as_mut_ptr的方法签名是:
pub fn as_mut_ptr(&mut self) -> *mut u8 {
self as *mut str as *mut u8
}
story明明是个不可变变量, 为什么可以作为可变引用传入方法?
sorry, 我搞错了!少看了一句
let mut story = mem::ManuallyDrop::new(story);
下面是完整代码
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!")
}
https://play.rust-lang.org/?version=stable&mode=debug&edition...
经过
let mut story = mem::ManuallyDrop::new(story);
,story 已经不是一个 String ,而是一个 stuct std::mem::ManuallyDrop<String>。它的 new 是这样的:原来的 immutable 的 String ,被 move 进了 mut ManuallyDrop<String> 。
而 MuauallyDrop 实现了 trait DerefMut ,于是会发生 Deref Coercion:
(这里,
T
是ManuallyDrop<String>
,U
是String
)于是你可以在 mut ManuallyDrop<String> 上调用所有 String 的 mutable methods。