【发布时间】:2016-03-09 07:39:46
【问题描述】:
我正在围绕 C 库编写 Rust 包装器,同时我试图利用 The Book 中提到的“可空指针优化”,但我找不到转换 @ 的好方法987654322@ 到 *const T 和 Option<&mut T> 到 *mut T 就像他们所描述的那样。
我真正想要的是能够打电话给Some(&foo) as *const _。不幸的是,这不起作用,所以我能想到的下一个最好的事情是Option<T> 的一个特征,它使我能够调用Some(&foo).as_ptr()。以下代码是该特征的工作定义和实现:
use std::ptr;
trait AsPtr<T> {
fn as_ptr(&self) -> *const T;
}
impl<'a, T> AsPtr<T> for Option<&'a T> {
fn as_ptr(&self) -> *const T {
match *self {
Some(val) => val as *const _,
None => ptr::null(),
}
}
}
现在我可以致电Some(&foo).as_ptr() 来获得*const _,我希望能够致电Some(&mut foo).as_ptr() 来获得*mut _。以下是我为此创建的新特征:
trait AsMutPtr<T> {
fn as_mut_ptr(&self) -> *mut T;
}
impl<'a, T> AsMutPtr<T> for Option<&'a mut T> {
fn as_mut_ptr(&self) -> *mut T {
match *self {
Some(val) => val as *mut _,
None => ptr::null_mut(),
}
}
}
问题是,AsMutPtr trait 无法编译。当我尝试时,我收到以下错误:
error[E0507]: cannot move out of borrowed content
--> src/lib.rs:22:15
|
22 | match *self {
| ^^^^^
| |
| cannot move out of borrowed content
| help: consider removing the `*`: `self`
23 | Some(val) => val as *mut _,
| --- data moved here
|
note: move occurs because `val` has type `&mut T`, which does not implement the `Copy` trait
--> src/lib.rs:23:18
|
23 | Some(val) => val as *mut _,
| ^^^
我看不出导致它失败的两个特征之间有什么变化——我不认为添加 mut 会产生那么大的不同。我尝试添加ref,但这只会导致不同的错误,而且我也不希望需要它。
为什么AsMutPtr 特征不起作用?
【问题讨论】: