如何解决如何围绕借入的值实现新类型的包装器?
我试图围绕借入的值实现一个新类型的包装器,以实现特征的不同行为,但无法使其符合借入规则。我在下面准备了一个简化的示例。
注意:The actual code is more complex并且还需要先处理需要.as_any().downcast_ref()
的值,这就是为什么我希望此值可以处理借来的值。
use std::cmp::Ordering;
trait OrdVec {
fn cmp(&self,i: usize,j: usize) -> Ordering;
}
// note: actual trait bound is more complex and would lead to
// "conflicting implementations" when trying to implement `OrdSlice for &[f64]`
impl<T> OrdVec for Vec<T>
where
T: Ord,{
fn cmp(&self,j: usize) -> Ordering {
self[i].cmp(&self[j])
}
}
#[repr(transparent)]
struct F64VecAsOrdVec<'a>(&'a Vec<f64>);
impl OrdVec for F64VecAsOrdVec<'_> {
fn cmp(&self,j: usize) -> Ordering {
let a: f64 = self.0[i];
let b: f64 = self.0[j];
if a < b {
return Ordering::Less;
}
if a > b {
return Ordering::Greater;
}
unimplemented!("convert NaN to canonical form and compare bitwise")
}
}
fn as_ord_vec<'a>(first: bool,int_vec: &'a Vec<i64>,float_vec: &'a Vec<f64>) -> &'a dyn OrdVec {
if first {
int_vec
} else {
// returns a reference to data owned by the current function
&F64VecAsOrdVec(float_vec)
// newtype should have same layout but this fails on calling `cmp`
// with "SIGSEGV: invalid memory reference"
// let ord: &F64VecAsOrdVec = unsafe { std::mem::transmute(float_vec) };
// ord
}
}
#[test]
fn test_int_as_ord() {
let int_vec = vec![1,2,3];
let float_vec = vec![3.0,2.0,1.0];
let int_ord = as_ord_vec(true,&int_vec,&float_vec);
assert_eq!(Ordering::Less,int_ord.cmp(0,1));
}
#[test]
fn test_float_as_ord() {
let int_vec = vec![1,1.0];
let float_ord = as_ord_vec(false,&float_vec);
assert_eq!(Ordering::Greater,float_ord.cmp(0,1));
}
error[E0515]: cannot return reference to temporary value
--> src/lib.rs:43:5
|
43 | &F64VecAsOrdVec(vec)
| ^-------------------
| ||
| |temporary value created here
| returns a reference to data owned by the current function
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。