有没有一种安全的方法可以从 Rust 中的可变引用中临时检索拥有的值? [复制]

2023-12-20

我正在使用两个独立的函数。

  • 第一个获取结构的自有实例然后返回它。
  • 第二个函数采用可变引用,但需要使用第一个函数。
// This structure is not `Clone`.
struct MyStruct;

fn take_owned(s: MyStruct) -> MyStruct {
    // Do things
    s
}

fn take_mut(s: &mut MyStruct) {
    *s = take_owned(s /* problem */);
}

我想到了一个解决方案,但我不确定它是否合理:

use std::ptr;

// Temporarily turns a mutable reference into an owned value.
fn mut_to_owned<F>(val: &mut MyStruct, f: F)
where
    F: FnOnce(MyStruct) -> MyStruct,
{
    // We're the only one able to access the data referenced by `val`.
    // This operation simply takes ownership of the value.
    let owned = unsafe { ptr::read(val) };

    // Do things to the owned value.
    let result = f(owned);

    // Give the ownership of the value back to its original owner.
    // From its point of view, nothing happened to the value because we have
    // an exclusive reference.
    unsafe { ptr::write(val, result) };
}

使用这个函数,我可以做到这一点:

fn take_mut(s: &mut MyStruct) {
    mut_to_owned(s, take_owned);
}

这段代码合理吗?如果没有,有没有办法安全地做到这一点?


有人已经在名为的箱子中实现了您正在寻找的内容take_mut https://docs.rs/take_mut/0.2.2/take_mut/.

函数 take_mut::take

pub fn take<T, F>(mut_ref: &mut T, closure: F) 
where
    F: FnOnce(T) -> T, 

允许使用指向的值&mut T就像它被拥有一样,只要T之后即可使用。

...

如果关闭发生恐慌,将中止程序。

函数 take_mut::take_or_recover

pub fn take_or_recover<T, F, R>(mut_ref: &mut T, recover: R, closure: F) 
where
    F: FnOnce(T) -> T,
    R: FnOnce() -> T, 

允许使用指向的值&mut T就像它被拥有一样,只要T之后即可使用。

...

将取代&mut T with recover if the closure恐慌,然后继续恐慌。

实现本质上就是您所拥有的,加上所描述的恐慌处理。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有一种安全的方法可以从 Rust 中的可变引用中临时检索拥有的值? [复制] 的相关文章

随机推荐