哪种类型对方法的`self`参数有效?

问题描述 投票:9回答:2

我想创建一个只适用于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>`

这是Rust 1.15.1。

methods syntax rust
2个回答
12
投票

在Rust 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() {}

Originally,Rust没有这种明确的self形式,只有self&self&mut self~selfBox的旧名称)。这改变了,只有按值和按引用具有简写内置语法,因为它们是常见的情况,并且具有非常关键的语言属性,而所有智能指针(包括Box)都需要显式形式。

从Rust 1.33开始,some additional selected types可用作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下进行,讨论正在the tracking issue 44874进行。

(值得期待的东西!)


2
投票

现在可以为self使用任意类型,包括Arc<Self>,但该功能被认为是不稳定的,因此需要添加此crate attribute

#![feature(arbitrary_self_types)]

使用feature crate属性需要使用每晚Rust。

© www.soinside.com 2019 - 2024. All rights reserved.