我正在阅读 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) .
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
的类型仍然有用。
另见:
请注意,以上所有内容对于 Index
和 IndexMut
也是有效的。
关于pointers - 为什么 Deref::deref 的返回类型本身就是一个引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31624743/