这个简单的程序:
fn main() {
let b: Box<i32> = Box::new(1);
b.into_raw();
}
Run Code Online (Sandbox Code Playgroud)
使用Rust 1.12.0编译时产生这个不方便的错误:
error: no method named `into_raw` found for type `Box<i32>` in the current scope
--> <anon>:3:7
|
3 | b.into_raw();
| ^^^^^^^^
|
= note: found the following associated functions; to be used as methods, functions must have a `self` parameter
= note: candidate #1 is defined in an impl for the type `Box<_>`
Run Code Online (Sandbox Code Playgroud)
这是因为into_raw未定义self为参数,而是定义为:
impl Box<T: ?Sized> {
fn into_raw(b: Box<T>) -> *mut T;
}
Run Code Online (Sandbox Code Playgroud)
这似乎不方便,我找不到理由.
所以为什么?
由于时间的99.995%(统计完全是编造的),你期望的方法调用发生的事情被指向到,而不是指针本身.因此,Rust中的"智能指针"类型通常会避免做任何事情来打破这种期望.一个明显的例外是Rc/ 直接Arc实现Clone.