0

Why does this code work?

trait T: std::fmt::Debug {
    fn func(mut self: Box<Self>) -> Box<T>;
}

#[derive(Debug)]
struct S {
    i: i32,
}

impl T for S {

    fn func(mut self: Box<Self>) -> Box<T> {
        self.as_mut().i += 1;
        self
    }
}

impl S {
    fn new() -> Box<S> {
        Box::new(S{i: 0})
    }
}

fn main() {
    let s = S::new();
    let s_inc = s.func();
    print!("{:?}", s_inc);
}

(Playground)

In particular, I don't understand how the type annotation mut self: Box<Self> in

impl T for S {
    fn func(mut self: Box<Self>) -> Box<T> {
        // ...
    }
}

works. Shouldn't self be of type S, not Box<S>? Which part of the method rules allow for this syntax?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
George
  • 131
  • 2
  • 8
  • 1
    Duplicate of http://stackoverflow.com/q/25462935/155423 ? – Shepmaster Jun 21 '16 at 22:45
  • Not exactly the same question but that response answers my question. Apparently `Box` is a valid type for `self`, which wasn't made clear in the rust-book. – George Jun 21 '16 at 23:39

0 Answers0