【发布时间】:2018-11-22 20:35:44
【问题描述】:
我有一个将一些功能包装在切片周围的结构:
use std::fmt::Debug;
struct SliceWrapper<'a, T: Debug + Copy + 'a> {
slice: &'a [T],
pos: usize,
}
我想为每个支持 AsRef<T: Debug + Copy + 'a> 的元素实现 From 特征,如下所示:
impl<'a, T: Debug + Copy + 'a, R: AsRef<[T]> + 'a> From<R> for SliceWrapper<'a, T> {
fn from(slice: R) -> Self {
Self {
slice: slice.as_ref(),
pos: 0,
}
}
}
我得到错误:
error[E0597]: `slice` does not live long enough
--> src/lib.rs:11:20
|
11 | slice: slice.as_ref(),
| ^^^^^ borrowed value does not live long enough
...
14 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 8:6...
--> src/lib.rs:8:6
|
8 | impl<'a, T: Debug + Copy + 'a, R: AsRef<[T]> + 'a> From<R> for SliceWrapper<'a, T> {
| ^^
我不明白这一点,因为我说R (slice) 必须和我的SliceWrapper 一样长——据我了解,AsRef<_> 继承了它的生命周期 self (slice)...
【问题讨论】:
标签: generics rust traits lifetime