What types are valid for the `self` method parameter?

I wanted to create a method that only works where the self parameter was Rc . I saw that I could use Box , so I thought I could try to mimic how this works:

 use std::rc::Rc; use std::sync::Arc; struct Bar; impl Bar { fn consuming(self) {} fn reference(&self) {} fn owned(self: Box<Bar>) {} fn ref_count(self: Rc<Bar>) {} fn atomic_ref_count(self: Arc<Bar>) {} } fn main() {} 

Holds these errors:

 error[E0308]: mismatched method receiver --> src/main.rs:10:18 | 10 | fn ref_count(self: Rc<Bar>) {} | ^^^^ expected struct `Bar`, found struct `std::rc::Rc` | = note: expected type `Bar` = note: found type `std::rc::Rc<Bar>` error[E0308]: mismatched method receiver --> src/main.rs:11:25 | 11 | fn atomic_ref_count(self: Arc<Bar>) {} | ^^^^ expected struct `Bar`, found struct `std::sync::Arc` | = note: expected type `Bar` = note: found type `std::sync::Arc<Bar>` 

This is with Rust 1.13 and you can also see it in the playpen

+7
rust
source share
1 answer

They are currently valid:

 struct Foo; impl Foo { fn by_val(self: Foo) {} // aka by_val(self) fn by_ref(self: &Foo) {} // aka by_ref(&self) fn by_mut_ref(self: &mut Foo) {} // aka by_mut_ref(&mut self) fn by_box(self: Box<Foo>) {} // no short form } fn main() {} 

Until recently , Rust did not have this explicit form of self , only self , &self , &mut self and ~self (the old name Box ). This has changed so that only by value and by reference they have a short syntax, since they are common cases and have very important language properties, while all smart pointers (including Box ) require an explicit form.

However, impl processing impl not generalized according to the syntax, which means that non- Box pointers still do not work. I believe that this requires the so-called 'trait reform' , which has not yet been implemented.

The current discussion is in issue 44874 .

(We are looking forward to something!)

+8
source share

All Articles