Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't `Box::into_raw` take `self` as parameter?

Tags:

rust

This simple program:

fn main() {
    let b: Box<i32> = Box::new(1);
    b.into_raw();
}

Produces this inconvenient error when compiled with 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<_>`

This is because into_raw is not defined to take self as parameter, but instead is defined as:

impl Box<T: ?Sized> {
    fn into_raw(b: Box<T>) -> *mut T;
}

This seems inconvenient, and I cannot find a rationale.

So... why?

like image 443
Matthieu M. Avatar asked Oct 21 '16 13:10

Matthieu M.


2 Answers

Because 99.995% of the time (statistic totally made up), you expect method calls to happen to the thing being pointed to, not to the pointer itself. As a result, the "smart pointer" types in Rust generally avoid doing anything to break that expectation. An obvious exception would be something like Rc/Arc implementing Clone directly.

like image 55
DK. Avatar answered Nov 26 '22 08:11

DK.


Box implements Deref, which means that all methods that are enclosed by the Box are automatically made available; from the outside, Box<T> and T look and act the same.

If into_raw were a method instead of an associated function, it would shadow any into_raw method on the contained type.

There are other examples of these enhancing associated functions on Rc, such as downgrade or try_unwrap, or on Arc, such as make_mut.

like image 33
Shepmaster Avatar answered Nov 26 '22 08:11

Shepmaster