gpt4 book ai didi

rust - 如何通过在 Rust 中实现 `Option` 来返回由 `Deref` 包装的引用?

转载 作者:行者123 更新时间:2023-11-29 08:31:10 24 4
gpt4 key购买 nike

我有一个包装器结构,它存储一个 Option 字段。我想获得对该字段中存储的数据的引用。以下代码编译。

struct Wrapper {
val: Option<i32>
}

impl Wrapper {
// lifetime specifier elided because Rust compiler can infer it
// to be fn my_deref<'a>(&'a self) -> Option<&'a i32>
fn my_deref(&self) -> Option<&i32> {
self.val.as_ref()
}
}

但是,我更喜欢为 Wrapper 实现 Deref 特性,这样我就可以进行解引用强制转换,这非常好。我尝试了以下代码,但编译器报错。

use std::ops::Deref;
struct Wrapper {
val: Option<i32>
}

impl Deref for Wrapper {
type Target = Option<&i32>; // It tells me I need a lifetime specifier.
fn deref(&self) -> Option<&i32> {
self.val.as_ref()
}
}

然后我尝试添加生命周期说明符,但又失败了。

use std::ops::Deref;
struct Wrapper<'a> { // It tells me 'a is never used.
val: Option<i32>
}

impl<'a> Deref for Wrapper<'a> {
type Target = Option<&'a i32>;
fn deref(&'a self) -> Option<&'a i32> {
self.val.as_ref()
}
}

实现与 my_deref 相同功能的 deref 的正确方法是什么?

最佳答案

阅读 turbulencetoo 的评论后,我想出了以下代码,它完全符合我的意图。根据程序逻辑,Option 字段永远不会是 None,因此我可以安全地解包它。由于与本主题无关的其他一些原因,我必须使用 Option 来包装它。

use std::ops::Deref;
struct Wrapper {
val: Option<i32>
}

impl Deref for Wrapper {
type Target = i32;
fn deref(&self) -> &i32 {
self.val.as_ref().unwrap()
}
}

下面引用 turbulencetoo 的评论。

Implementing Deref for T does not mean that you can get a U from a T! It means that you can get an &U from an &T. In this case, the new Option that is created by the as_ref call in the deref function is not the same Option that your Wrapper stores, and as such you can't return a reference to it.

关于rust - 如何通过在 Rust 中实现 `Option` 来返回由 `Deref` 包装的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57435244/

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