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

Pointers 为什么对Deref::Deref的结果进行断言会因类型不匹配而失败?,pointers,rust,Pointers,Rust,除了我添加了另一个断言之外,以下是最新的声明 为什么assert_eq与deref同样等于'a'?手动调用deref后,为什么需要* use std::ops::Deref; struct DerefExample<T> { value: T, } impl<T> Deref for DerefExample<T> { type Target = T; fn deref(&self) -> &T {

除了我添加了另一个断言之外,以下是最新的声明

为什么
assert_eq
deref
同样等于
'a'
?手动调用
deref
后,为什么需要
*

use std::ops::Deref;

struct DerefExample<T> {
    value: T,
}

impl<T> Deref for DerefExample<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.value
    }
}

fn main() {
    let x = DerefExample { value: 'a' };
    assert_eq!('a', *x.deref()); // this is true
    // assert_eq!('a', x.deref()); // this is a compile error
    assert_eq!('a', *x); // this is also true
    println!("ok");
}

首先,让我们为您的特定示例详细说明泛型类型:
'a'
char
,因此我们有:

impl Deref for DerefExample<char> {
    type Target = char;

    fn deref(&self) -> &char {
        &self.value
    }
}
impl Deref for DerefExample{
类型Target=char;
fn deref(&self)->&char{
&自我价值
}
}
值得注意的是,
deref
的返回类型是对
char
的引用。因此,当您仅使用
x.deref()
时,结果是
&char
而不是
char
,这并不奇怪。请记住,此时,
deref
只是另一个普通方法——它只是作为某些语言提供的特殊语法的一部分隐式调用的<例如,code>*x将调用
deref
并在适用时取消引用结果
x.char\u method()
fn\u taking\u char(&x)
也会调用
deref
多次,然后进一步处理结果

您会问,为什么
deref
首先返回一个引用?那不是圆形的吗?不,它不是循环的:它减少了指向内置类型
&t
的库定义的智能指针,编译器已经知道如何取消引用该类型。通过返回引用而不是值,可以避免复制/移动(这可能并不总是可能的!),并允许
&*x
(或在强制时
&x
)引用
DerefExample
保存的实际
字符,而不是临时副本

另见:


谢谢您的回答。当你说“*x,例如,将调用deref并取消引用结果”时,我认为你的意思是字面上有两件事正在发生,首先调用deref以获得(&)引用,然后“取消引用”以获得对字符的访问。