Gym*_*ore 3 unsafe ownership 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 */);
}
Run Code Online (Sandbox Code Playgroud)
我想了一个解决方案,但我不确定它是否合理:
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) };
}
Run Code Online (Sandbox Code Playgroud)
使用此功能,我可以做到:
fn take_mut(s: &mut MyStruct) {
mut_to_owned(s, take_owned);
}
Run Code Online (Sandbox Code Playgroud)
这段代码好听吗?如果没有,有没有办法安全地做到这一点?
有人已经在名为take_mut.
函数 take_mut::take
Run Code Online (Sandbox Code Playgroud)pub fn take<T, F>(mut_ref: &mut T, closure: F) where F: FnOnce(T) -> T,允许使用指向的值,
&mut T就好像它是拥有的一样,只要 aT之后可用。...
如果关闭发生恐慌,将中止程序。
函数 take_mut::take_or_recover
Run Code Online (Sandbox Code Playgroud)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
实现基本上就是你所拥有的,加上所描述的恐慌处理。