简体   繁体   English

&self 在 Inner 结构上实现的 Deref 特征中指的是什么?

[英]What does &self refer to in the Deref trait implemented on the Inner struct?

I've found this piece of code on a reddit post that is very confusing to me.我在 reddit 帖子上发现了这段代码,这让我很困惑。

//We'll recurse all we want, thank you very much!
#![allow(unconditional_recursion)]

use std::ops::Deref;

#[derive(Debug)]
struct Outer<T: Deref<Target = Outer<T>>> {
    inner: T,
}

impl<T: Deref<Target = Outer<T>>> Deref for Outer<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

#[derive(Debug)]
struct Inner {}

impl Deref for Inner {
    type Target = Outer<Inner>;

    fn deref(&self) -> &Self::Target {
        //Look at which struct we're implementing Deref for,
        //and then read the next line very carefully.
        &self.inner
    }
}

const I: Inner = Inner {};
const O: Outer<Inner> = Outer { inner: I };

fn main() {
    println!("{:?}", O.inner);
    //Could just keep adding asterisks forever!
    println!("{:?}", *O.inner);
    println!("{:?}", **O.inner);
    println!("{:?}", ***O.inner);

    println!("{:?}", O);
    //Could just keep adding asterisks forever!
    println!("{:?}", *O);
    println!("{:?}", **O);
    println!("{:?}", ***O);
}

Specifically here:具体在这里:

impl Deref for Inner {
    type Target = Outer<Inner>;

    fn deref(&self) -> &Self::Target {
        //Look at which struct we're implementing Deref for,
        //and then read the next line very carefully.
        &self.inner
    }
}

How does the function return a reference to a field that belongs to another struct?函数如何返回对属于另一个结构的字段的引用? Does &self actually refer to Outer here? &self 实际上在这里指的是 Outer 吗?

(Also this code crashes every time from stack overflow) (此代码每次因堆栈溢出而崩溃)

Indeed there is no inner on Inner .确实, Inner上没有inner But before giving up, the compiler thinks, "wait, is there some Deref implementation for Inner ?"但在放弃之前,编译器会想,“等等,是否有一些InnerDeref实现?” and of course the answer is, there is!答案当然是,有! We're writing it right now!我们现在就写! So, what does it return?那么,它返回了什么? Outer<Inner> ? Outer<Inner> Well, try to deref and find inner on Outer<Inner> !好吧,尝试 deref 并在Outer<Inner>上找到inner That is, &self.inner gets transformed into &<Self as Deref>::deref(&self).inner .也就是说, &self.inner被转换为&<Self as Deref>::deref(&self).inner That is autoderef in action.这就是autoderef的作用。

Of course, since we are already inside <Inner as Deref>::deref() , we call it again, recursively... and again... and again... until we blow the stack.当然,由于我们已经<Inner as Deref>::deref()内部,我们再次递归地调用它......再......再......直到我们破坏堆栈。 If you'll remove the #[allow(unconditional_recursion)] at the top, the compiler will warn you about that ( playground ):如果您删除顶部的#[allow(unconditional_recursion)] ,编译器会警告您( 操场):

warning: function cannot return without recursing
  --> src/main.rs:22:5
   |
22 |     fn deref(&self) -> &Self::Target {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot return without recursing
...
25 |         &self.inner
   |          ---------- recursive call site
   |
   = note: `#[warn(unconditional_recursion)]` on by default
   = help: a `loop` may express intention better if this is on purpose

But when you say #[allow(unconditional_recursion)] , you tell the compiler "trust me, I know what I'm doing" so it just shrugs and continues.但是当你说#[allow(unconditional_recursion)]时,你告诉编译器“相信我,我知道我在做什么”,所以它只是耸耸肩并继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在拥有盒装特征的结构上实现Deref - Implementing Deref on a struct that owns a boxed trait 无法在已实现的方法中序列化结构,因为“没有为 `Self` 实现特征 `serde::Serialize`” - Can't serialize a struct in an implemented method because “the trait `serde::Serialize` is not implemented for `Self`” 如何为包含Rc的结构实现Deref <Refcell<Trait> &gt;? - How can I implement Deref for a struct that holds an Rc<Refcell<Trait>>? Rust 结构字段泛型超过 Deref<target=self></target=self> - Rust struct field generic over Deref<Target=Self> Rust:“该特征没有为 Self 实现”,即使它完全是 - Rust: "the trait is not implemented for Self" even though it totally is 返回实现的结构的通用异步特征 - Generic async trait that returns the implemented Struct 当通用结构实现“Deref”时,实际会生成什么代码? - What code will actually be generated when a generic struct implements `Deref`? 如何使用特征对象来引用具有泛型方法的struct - How to use a trait object to refer to struct that has generic methods Rust 编译器无法识别为结构实现的通用特征绑定 - Rust compiler not recognizing a generic trait bound implemented for a struct 特性`diesel::Insertable<schema::trd::table> ` 没有实现<Struct> - The trait `diesel::Insertable<schema::trd::table>` is not implemented for <Struct>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM