为什么 Deref::deref 的返回类型本身就是一个引用?

编程入门 行业动态 更新时间:2024-10-28 08:16:45
本文介绍了为什么 Deref::deref 的返回类型本身就是一个引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在阅读 Rust 的文档 Deref 特质:

I was reading the docs for Rust's Deref trait:

pub trait Deref { type Target: ?Sized; fn deref(&self) -> &Self::Target; }

deref 函数的类型签名对我来说似乎违反直觉;为什么返回类型是引用?如果引用实现了这个特性以便它们可以被取消引用,这会产生什么影响?

The type signature for the deref function seems counter-intuitive to me; why is the return type a reference? If references implement this trait so they can be dereferenced, what effect would this have at all?

我能想到的唯一解释是引用没有实现Deref,而是被认为是原始可取消引用的".但是,如何编写适用于 任何 可解引用类型的多态函数,包括 Deref 和 &T,然后?

The only explanation that I can come up with is that references don't implement Deref, but are considered "primitively dereferenceable". However, how would a polymorphic function which would work for any dereferenceable type, including both Deref<T> and &T, be written then?

推荐答案

引用没有实现Deref

你可以看到所有实现Deref的类型 和 &T 在该列表中:

You can see all the types that implement Deref, and &T is in that list:

impl<'a, T> Deref for &'a T where T: ?Sized

不明显的是,当您将 * 运算符与实现 Deref 的东西一起使用时,会应用语法糖.看看这个小例子:

The non-obvious thing is that there is syntactical sugar being applied when you use the * operator with something that implements Deref. Check out this small example:

use std::ops::Deref; fn main() { let s: String = "hello".into(); let _: () = Deref::deref(&s); let _: () = *s; }

error[E0308]: mismatched types --> src/main.rs:5:17 | 5 | let _: () = Deref::deref(&s); | ^^^^^^^^^^^^^^^^ expected (), found &str | = note: expected type `()` found type `&str` error[E0308]: mismatched types --> src/main.rs:6:17 | 6 | let _: () = *s; | ^^ expected (), found str | = note: expected type `()` found type `str`

对deref 的显式调用返回一个&str,但操作符* 返回一个str.这更像是您在调用 *Deref::deref(&s),忽略隐含的无限递归 (参见文档).

The explicit call to deref returns a &str, but the operator * returns a str. It's more like you are calling *Deref::deref(&s), ignoring the implied infinite recursion (see docs).

Xirdus 说得对

如果 deref 返回一个值,它要么是无用的,因为它总是会移出,要么具有与其他函数截然不同的语义

If deref returned a value, it would either be useless because it would always move out, or have semantics that drastically differ from every other function

虽然没用"有点强;它对于实现 Copy 的类型仍然很有用.

Although "useless" is a bit strong; it would still be useful for types that implement Copy.

另见:

  • 为什么对 Deref::deref 的结果进行断言会因类型不匹配而失败?

请注意,上述所有内容对于 Index 和 IndexMut 都有效.

Note that all of the above is effectively true for Index and IndexMut as well.

更多推荐

为什么 Deref::deref 的返回类型本身就是一个引用?

本文发布于:2023-09-22 22:07:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466890.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   Deref   deref

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!