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

标签 pointers reference rust

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

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

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

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

最佳答案

that references don't implement Deref

可以看到all the types that implement Deref ,并且 &T 在该列表中:

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

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

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),忽略隐含的无限递归 (see docs) .

Xirdus is correct in saying

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 的类型仍然有用。

另见:

请注意,以上所有内容对于 IndexIndexMut 也是有效的。

关于pointers - 为什么 Deref::deref 的返回类型本身就是一个引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31624743/

相关文章:

c++ - 通过指针打印矩阵

c - 从不兼容的指针类型传递参数 1( 'strcmp')

debugging - 如何查看导致我的编译错误的扩展宏代码?

c++ - 为什么不能在 C++ 中重新初始化引用?

c++ - 按位常量和指针 :

perl - 对相等字符串的引用

rust - 两个可变借用发生在同一条线上?

rust - 如何将 Future 作为函数参数传递?

c++ - 如果首先使用非常量初始化,为什么允许对 const 的非常量引用?

Java:为什么两者都引用同一个对象?