gpt4 book ai didi

rust - 从功能参数实现具有生命周期限制的切片的特征

转载 作者:行者123 更新时间:2023-12-03 11:33:33 26 4
gpt4 key购买 nike

在以下代码段中,我正在尝试实现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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com