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

我正在使用两个独立的功能。

  • 第一个获取结构的拥有实例,然后返回它。
  • 第二个采用可变引用但需要使用第一个函数。
// 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.

函数 take_mut::take

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

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

...

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

函数 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就好像它是拥有的一样,只要 aT之后可用。

...

如果恐慌,将替换&mut T为,然后继续恐慌。recoverclosure

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


以上是有没有一种安全的方法可以从Rust的可变引用中临时检索一个拥有的值?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>