gpt4 book ai didi

methods - 什么类型对方法的 `self` 参数有效?

转载 作者:行者123 更新时间:2023-11-29 07:42:25 25 4
gpt4 key购买 nike

我想创建一个仅在 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。

最佳答案

在 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 ~self(Box 的旧名称)。这发生了变化,因此只有按值和按引用具有简写内置语法,因为它们是常见的情况,并且具有非常关键的语言属性,而所有智能指针(包括 Box ) 需要明确的形式。

从 Rust 1.33 开始,some additional selected types可用作 self:

  • Rc
  • 圆Arc
  • 固定

这意味着原来的例子现在可以工作了:

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 中进行讨论。 .

(值得期待的东西!)

关于methods - 什么类型对方法的 `self` 参数有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25462935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com