为什么`Box::into_raw`不以`self`作为参数?

10

这个简单的程序:

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个回答

9
因为99.995%的时间(统计数据完全虚构),{{link1:您期望方法调用发生在指向的对象上,而不是指针本身}}。 因此,Rust中的“智能指针”类型通常避免做任何破坏该期望的事情。 显然的例外是像Rc/Arc直接实现Clone这样的情况。

啊谢谢!我一直在错误的方向上绞尽脑汁,没有考虑到大多数方法调用是通过 Defer 转发给 pointee 的。 - Matthieu M.

8
Box 实现了 Deref,这意味着所有被 Box 包含的方法都会自动地可用;从外部看来,Box<T>T 看起来和行为相同。
如果 into_raw 是一个方法而不是关联函数,则会遮盖包含类型上的任何 into_raw 方法。
还有其他例子可以增强关联函数,例如在 Rc 上的 downgradetry_unwrap,或者在 Arc 上的 make_mut

2
请查看将这些函数添加到标准库的拉取请求 - George Hilliard
@thirtythreeforty:确实是一个很好的资源,alexcrichton的评论解释得非常清楚。 - Matthieu M.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接