为什么 Deref::deref 的返回类型本身就是一个引用? [英] Why is the return type of Deref::deref itself a reference?

查看:29
本文介绍了为什么 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.

另见:

请注意,上述所有内容对于 IndexIndexMut 都有效.

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

这篇关于为什么 Deref::deref 的返回类型本身就是一个引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆