哪些类型是有效的方法的`self`参数?哪些类型是有效的方法的`self`参数?(What type

2019-05-12 05:32发布

我想创造只能在一个方法self参数是一个Rc 。 我看到了,我可以用Box ,所以我想我可能会尝试模仿如何工作的:

use std::rc::Rc;
use std::sync::Arc;

struct Bar;

impl Bar {
    fn consuming(self) {}
    fn reference(&self) {}
    fn mutable_reference(&mut self) {}
    fn boxed(self: Box<Bar>) {}
    fn ref_count(self: Rc<Bar>) {}
    fn atomic_ref_count(self: Arc<Bar>) {}
}

fn main() {}

产生这些错误:

error[E0308]: mismatched method receiver
  --> a.rs:11:18
   |
11 |     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
  --> a.rs:12:25
   |
12 |     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>`

这是铁锈1.15.1。

Answer 1:

锈1.33之前,只有四种有效方法接收机:

struct Foo;

impl Foo {
    fn by_val(self: Foo) {} // a.k.a. by_val(self)
    fn by_ref(self: &Foo) {} // a.k.a. by_ref(&self)
    fn by_mut_ref(self: &mut Foo) {} // a.k.a. by_mut_ref(&mut self)
    fn by_box(self: Box<Foo>) {} // no short form
}

fn main() {}

本来 ,锈没有这种明确的self形式,只有self&self&mut self~self (古称Box )。 这种改变,这样只值和通过引用有速记内置语法,因为它们是常见的情况,并有非常关键的语言特性,而所有的智能指针(包括Box )需要明确的形式。

铁锈1.33, 其他一些选择的类型都可以用作self

  • Rc
  • Arc
  • Pin

这意味着,原来的例子现在工作:

use std::{rc::Rc, sync::Arc};

struct Bar;

impl Bar {
    fn consuming(self)                  { println!("self") }
    fn reference(&self)                 { println!("&self") }
    fn mut_reference(&mut self)         { println!("&mut self") }
    fn boxed(self: Box<Bar>)            { println!("Box") }
    fn ref_count(self: Rc<Bar>)         { println!("Rc") }
    fn atomic_ref_count(self: Arc<Bar>) { println!("Arc") }
}

fn main() {
    Bar.consuming();
    Bar.reference();
    Bar.mut_reference();
    Box::new(Bar).boxed();
    Rc::new(Bar).ref_count();
    Arc::new(Bar).atomic_ref_count();
}

然而, impl处理尚未完全推广到符合语法,所以用户创建的类型仍然不工作。 这一进展正在下的功能标志做出arbitrary_self_types和讨论正在发生的跟踪问题44874 。

(有什么期待!)



Answer 2:

现在已经可以使用任意类型self ,包括Arc<Self> ,但该功能被认为是不稳定的,因此需要添加这个箱子属性 :

#![feature(arbitrary_self_types)]

使用feature箱属性需要使用夜间生锈。



文章来源: What types are valid for the `self` parameter of a method?