gpt4 book ai didi

indexing - 使用生命周期实现索引特征

转载 作者:行者123 更新时间:2023-12-05 01:06:51 24 4
gpt4 key购买 nike

我想为这个结构重载索引操作符:

struct Ram<'a> {
ram: &'a mut [u8]
}

impl<'a> Ram<'a> {
pub fn new( bytes: &mut[u8]) -> Ram {
Ram {
ram: bytes
}
}
}

... 它基本上是一个字节数组的“ Controller ”。我这样做是因为我想将它重用于不同大小的字节数组。我知道生命周期是为了确保“ram”引用在整个执行过程中有效。这是我当前的索引代码:

use std::ops::{Index};
impl<'a> Index<usize> for Ram<'a> {
type Output = u8;
fn index(&self, i: usize) -> &'a u8 {
&self.ram[i]
}
}

这不会编译。 Rust 说有一个匿名生命周期定义与 index(...) 定义中的 'a 冲突:“错误[E0495]:由于要求冲突,无法推断函数调用中生命周期参数的适当生命周期”。

我应该如何实现它?还是我对生命的假设完全错误?谢谢。

最佳答案

您不需要指定返回引用的生命周期(注意 -> &u8)。 Playground .

错误是因为 Index trait 要求对象的生命周期说明符 (&self) 和返回值 (&u8) 相同 (这相当于要求 &self至少只要返回的引用)。

为了简化编码,Rust 允许跳过显式指定此生命周期,因此留下 &self&u8 与指定 &'x self&'x u8。您只明确指定了其中一个引用的生命周期,从而混淆了编译器。

use std::ops::{Index};
impl<'a> Index<usize> for Ram<'a> {
type Output = u8;
fn index(&self, i: usize) -> &u8 {
&self.ram[i]
}
}

fn main() {
let mut _ram = [0, 1, 2, 3];
let ram_holder = Ram::new(&mut _ram);
println!("{}", ram_holder[1]);
// prints: 1
}

关于indexing - 使用生命周期实现索引特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68358481/

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