From 特性似乎不适用于此用例.该特征的想法是将某些数据的所有权移至新的类型,但是您的 SliceWrapper 不具有所有权.我建议写一个自定义构造函数,而不是引用 R .I have a struct that wraps some functionality around a slice:use std::fmt::Debug;struct SliceWrapper<'a, T: Debug + Copy + 'a> { slice: &'a [T], pos: usize,}I want to implement the From trait for each element that supports AsRef<T: Debug + Copy + 'a> like this: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, } }}I get the error: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> { | ^^I don't understand this because I say that R (slice) must live as long as my SliceWrapper – and as far as I understand it, AsRef<_> inherits the lifetime from it's self (slice)... 解决方案 The full error message on nightly states quite clearly what's happening here. You move slice into the function from(), then borrow it using as_ref(), and then it gets dropped at the end of the scope:8 | impl<'a, T: Debug + Copy + 'a, R: AsRef<[T]> + 'a> From<R> for SliceWrapper<'a, T> { | -- lifetime `'a` defined here9 | fn from(slice: R) -> Self {10 | Self{ slice: slice.as_ref(), pos: 0 } | ^^^^^--------- | | | borrowed value does not live long enough | argument requires that `slice` is borrowed for `'a`11 | } | - `slice` dropped here while still borrowedYou are trying to create a borrow that lives for the lifetime 'a, but the owner you are borrowing from, slice, does not live long enough.The From trait does not seem to be a good fit for this use case. The idea of that trait is to move ownership of some data to a new type, but your SliceWrapper does not take ownership. I suggest writing a custom constructor instead that takes R by reference. 这篇关于即使“自身"寿命足够长,借入的值也无法为"AsRef"结果提供足够的寿命的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-14 13:10