gpt4 book ai didi

rust - * 和 deref 方法有什么区别?

转载 作者:行者123 更新时间:2023-12-03 11:37:19 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Why is the return type of Deref::deref itself a reference?

(2 个回答)


1年前关闭。




例如,我有一个实现了 Deref 的结构

use std::ops::{Deref, DerefMut, IndexMut};

#[derive(Debug)]
struct Selector<T> {
elements: Vec<T>,
current: usize
}

impl<T> Deref for Selector<T> {
type Target = T;
fn deref(&self) -> &T {
&self.elements[self.current]
}
}

impl<T> DerefMut for Selector<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.elements[self.current]
}
}
然后我做 *s = 'w';这意味着 rust 正在做 &s.elements[s.current] = 'w's.elements.index_mut(s.current) = 'w'; 相同
除了 index_mut 返回一个引用,你不能分配一个引用,所以我将上面的内容更改为 *&mut *s.elements.index_mut(s.current) = 'w';所以 *s*s.deref_mut() 相同deref_mut 是我对 Deref 的实现。所以这让我认为 *s更像 **s , 其中第一个 *调用我的 deref_mut 方法和第二个 *将结果 &mut T进入 mut T . rust 在我实现 Deref 之后是否添加了另一个 deref 方法,因为 deref_mut 返回一个引用?如果是这样,这叫什么?
这是否意味着 *并且 deref 方法是不同的,其中一个跟随指向数据的指针,而另一个允许您对引用执行某些操作,然后返回另一个引用? rust 是否隐式插入另一个 *转换引用?

最佳答案

如果 x有类型 &T&mut T ,然后 *x有类型 T .
如果 x有一些其他类型S ?如果 S实现 DerefDerefMut , 那么 Rust 会调用 .deref().deref_mut()x ,并取消引用。

Does this mean that * and the deref method are different where one follows a pointer to data and the other one allows you to do something to a reference and then return another reference?


是的。一元 *运算符跟在引用之后,而 deref 特征将非引用强制转换为引用。

关于rust - * 和 deref 方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62505556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com