在以下代码段中,我正在尝试实现C:
// A
trait Get {
fn get(slice: &[f32]) -> Self;
}
// B
impl Get for () {
fn get(slice: &[f32]) -> Self {
()
}
}
// C
impl Get for &[f32] {
fn get(slice: &[f32]) -> Self {
&slice[0..5]
}
}
但是,这不起作用,因为借用检查器(正确地)提示外部&[f32]
的生存期与slice
的生存期不匹配。我如何表达这一点,最好不要改变其特质?我尝试了以下方法,但没有结果:
// Doesn't work because the function signature differs from the Trait
impl<'a> Get for &'a [f32] {
fn get(slice: &'a [f32]) -> Self {
&slice[0..5]
}
}
// Doesn't work, because the trait bound is not the same as the trait function
impl<'b> Get for &'b [f32] {
fn get<'a>(slice: &'a [f32]) -> Self where 'a: 'b {
&slice[0..5]
}
}
最佳答案
如何在整个Get
生命周期内使'a
通用:
trait Get<'a> {
fn get(slice: &'a [f32]) -> Self;
}
impl<'a> Get<'a> for () {
fn get(slice: &'a [f32]) -> Self {
()
}
}
impl<'a> Get<'a> for &'a [f32] {
fn get(slice: &'a [f32]) -> Self {
&slice[0..5]
}
}
关于rust - 从功能参数实现具有生命周期限制的切片的特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66241288/