为什么没有'Box :: into_raw`把'self`作为参数?

时间:2016-10-21 13:49:23

标签: rust

这个简单的程序:

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;
}

这似乎不方便,我找不到理由。

那么......为什么?

2 个答案:

答案 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)

Box实现Deref,这意味着Box所包含的所有方法都会自动生效;从外面看,Box<T>T看起来和行为相同。

如果into_raw是一个方法而不是一个关联的函数,它会影响所包含类型的任何into_raw方法。

Rc上有这些增强相关功能的其他示例,例如downgradetry_unwrapArc,例如make_mut。< / p>