gpt4 book ai didi

rust - 将选项> 转换为选项<&T>

转载 作者:行者123 更新时间:2023-12-05 09:28:19 24 4
gpt4 key购买 nike

我们知道很容易转换类型为 RefCell<T> 的值到 &T 类型的值用作函数中的参数:

fn main() {
let a: RefCell<i32> = RefCell::new(0);
my_func(a.borrow().deref());
}

fn my_func(i: &i32) {}

在我的场景中,RefCell s 存储在 HashMap 中, 所以他们得到包裹在 Option 中.我也希望我传递给他们的函数具有选项的概念,但我只想传递非可变引用,而不是整个 RefCell .我们可以这样实现:

fn main() {
let a: Option<RefCell<i32>> = Some(RefCell::new(0));

match a {
Some(ref_cell) => my_func(Some(ref_cell.borrow().deref())),
None => my_func(None)
};
}

fn my_func(i: Option<&i32>) {}

这行得通,但在我的特定情况下,my_func需要其中的几个 Option<&T> s 作为参数,所以这样做意味着 match只是为每个参数嵌套并呈指数增长。因此,以某种方式执行此操作会很有帮助:

fn main() {
let a: Option<RefCell<i32>> = Some(RefCell::new(0));

let c = match a {
Some(ref_cell) => Some(ref_cell.borrow().deref()), // won't compile as this borrow won't live long enough
None => None
};

my_func(c);
}

fn my_func(i: Option<&i32>) {}

所以基本上我希望能够从 Option<RefCell<T>> 转换至 Option<&T> .我觉得这在某种程度上应该是可能的,但我想不出办法去做。我总是遇到一些执行 .borrow() 的问题在 RefCell 上但它的生命周期不够长。

最佳答案

您可以使用 Option 上的方法执行此操作:

a.as_ref().map(RefCell::borrow).as_deref()
  • as_ref() 用于转换 Option<RefCell<_>>进入 Option<&RefCell<_>>以避免食用它。如果您已经有 Option<&RefCell<_>>因为你是从 hash_map.get() 得到的或类似的,那么你可以跳过这个。
  • map(RefCell::borrow) 用于调用.borrow()值(如果存在)。这将创建一个 Option<Ref<'_, _>> .
  • as_deref() 相当于调用 .deref()值(如果存在)。

重要的是这样做而不是试图合并 .borrow().deref()在一个.map()调用,因为这保留了中间 Ref<'_, _>活着的值(value)。

a.as_ref().map(|a| a.borrow().deref())
error[E0515]: cannot return reference to temporary value
--> src/main.rs:8:24
|
8 | a.as_ref().map(|a| a.borrow().deref())
| ----------^^^^^^^^
| |
| returns a reference to data owned by the current function
| temporary value created here

此外,如果有多个这样的参数并且您想将它们拆分成变量,请务必使用 Ref<'_, _>部分自己并使用.as_deref()你在哪里使用它。同样,这需要保持中间 Ref<'_, _>活着:

let a_ref = a.as_ref().map(RefCell::borrow);
let b_ref = b.as_ref().map(RefCell::borrow);
let c_ref = c.as_ref().map(RefCell::borrow);

f(a_ref.as_deref(), b_ref.as_deref(), c_ref.as_deref());

关于rust - 将选项<RefCell<T>> 转换为选项<&T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71461796/

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