为什么`box :: into_raw`不将`self`作为参数?

Mat*_* M. 10 rust

这个简单的程序:

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)

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

所以为什么?

DK.*_*DK. 9

由于时间的99.995%(统计完全是编造的),你期望的方法调用发生的事情被指向,而不是指针本身.因此,Rust中的"智能指针"类型通常会避免做任何事情来打破这种期望.一个明显的例外是Rc/ 直接Arc实现Clone.


She*_*ter 7

Box实现Deref,这意味着由它包围的所有方法Box都自动可用; 从外观看,Box<T>T看起来和用起来一样.

如果into_raw是方法而不是关联的函数,它将遮蔽into_raw所包含类型的任何方法.

有对这些增强相关联的功能的其他的例子Rc,例如downgradetry_unwrap,或上Arc,例如make_mut.

  • 请参阅[拉取请求](https://github.com/rust-lang/rust/pull/21318)将这些功能添加到标准库中. (2认同)