返回包含函数拥有的数据的数据

Raf*_*elo 5 rust

我想要一个DataAllocator可以返回具有生命周期的数据的数据'r,这样我就可以将它传递给something并且仍然能够返回内部分配的值something

use std::marker::PhantomData;

pub struct Data<'a, T>{
    a: &'a [T]
}

impl<'a, T> Data<'a, T> {
    pub fn new() -> Data<'a, T> {
        todo!()
    }
    
    fn iter(&'a self) -> Iter<'a, T> {
        todo!()
    }
}

pub struct Iter<'a, T> {
    _phantom: PhantomData<&'a T>
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;
    fn next(&mut self) -> Option<Self::Item> {
        todo!()
    }
}

pub trait DataAllocator<'s, 'r, T> {
    fn allocate(&'s self) -> Box<dyn AsRef<[T]> + 'r>;
}

impl<'s, 'r, T> DataAllocator<'s, 'r, T> for Data<'r, T> {
    fn allocate(&'s self) -> Box<dyn AsRef<[T]> + 'r> {
        todo!()
    }
}

fn do_something<'a, 'b, T>(data_allocator: &'a dyn DataAllocator<'a, 'b, T>) -> Data<'b, T> {
    let buffer = data_allocator.allocate();
    let data = Data{a: (*buffer).as_ref()};
    for e in data.iter(){}
    data
}
Run Code Online (Sandbox Code Playgroud)

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=2a3e0d0cdea86238413af25dddd04e19

error[E0515]: cannot return value referencing local data `*buffer`
  --> src/lib.rs:42:5
   |
40 |     let data = Data{a: (*buffer).as_ref()};
   |                        ------------------ `*buffer` is borrowed here
41 |     for e in data.iter(){}
42 |     data
   |     ^^^^ returns a value referencing data owned by the current function
Run Code Online (Sandbox Code Playgroud)

问题是,如果我尝试迭代data,那么它会抱怨我正在尝试返回函数借用的东西.iter().iter()我认为这可能与我所说的借用Data生命周期有关'b,这是分配数据的整个生命周期。这种情况我能做什么?

kmd*_*eko 4

我认为混淆在于.as_ref()返回dyn AsRef<[T]> + 'r一个与其自身相关的引用,而不是与'r生命周期相关的引用。因此,您获得的参考源自(*buffer).as_ref()buffer这当然超出了范围。

但很难说你应该对此做什么,因为这todo!()模糊了你计划如何实现这一目标。但根据我所看到的,我可能期望allocate()返回一个&'r [T]. 游乐场