这个简单的程序:
fn main() {
let b: Box<i32> = Box::new(1);
b.into_raw();
}
使用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<_>`
这是因为into_raw
未定义为self
作为参数,而是定义为:
impl Box<T: ?Sized> {
fn into_raw(b: Box<T>) -> *mut T;
}
这似乎不方便,我找不到理由。
那么......为什么?
答案 0 :(得分:9)
因为99.995%的时间(统计数据完全构成),you expect method calls to happen to the thing being pointed to, not to the pointer itself。结果,&#34;智能指针&#34; Rust 中的类型通常避免做任何事情来打破这种期望。一个明显的例外是直接实施Rc
的{{1}} / Arc
。
答案 1 :(得分:7)