【发布时间】:2019-03-15 05:03:29
【问题描述】:
考虑以下代码:
use std::ops;
struct Wrap<T>(T);
impl<T> Wrap<T> {
fn new(element: T) -> Self {
Wrap(element)
}
}
// implementation of other methods that makes the wrapper necessary ;-)
impl ops::Index<ops::Range<usize>> for Wrap<Vec<i8>> {
type Output = Wrap<&[i8]>;
fn index(&self, range: ops::Range<usize>) -> &Self::Output {
&Wrap::<&[i8]>::new(&self.0[range])
}
}
impl ops::Index<ops::Range<usize>> for Wrap<&[i8]> {
type Output = Wrap<&[i8]>;
fn index(&self, range: ops::Range<usize>) -> &Self::Output {
&Wrap::<&[i8]>::new(&self.0[range])
}
}
编译器声明:
error[E0106]: missing lifetime specifier
--> src/lib.rs:14:24
|
14 | type Output = Wrap<&[i8]>;
| ^ expected lifetime parameter
error[E0106]: missing lifetime specifier
--> src/lib.rs:21:45
|
21 | impl ops::Index<ops::Range<usize>> for Wrap<&[i8]> {
| ^ expected lifetime parameter
error[E0106]: missing lifetime specifier
--> src/lib.rs:22:24
|
22 | type Output = Wrap<&[i8]>;
| ^ expected lifetime parameter
我应该如何在这里设置生命周期?我希望Wrap 为拥有的Vecs 以及借来的切片工作。最好的解决方案是什么?
【问题讨论】:
-
Vec 已经实现
as_slice()所以我不明白这一点。你需要Cow<Vec<i8>>吗? -
是的,我遗漏了需要 Wrapper 的部分。我试图将代码集中在问题上。我知道还有其他方法可以实现这一点,但我认为最好的设计是包装器,并且觉得这应该是可能的。
标签: rust slice traits lifetime