I'm using Refcell and as below code, but got warning: cannot return value referencing temporary value.
I know this warning but don't know how to avoid it. anyone can help me on this, thanks advanced.
use std::cell::RefCell;
#[derive(Debug, Clone)]
enum D{
S(String),
F(f64)
}
#[derive(Debug, Clone)]
struct COL {
title: String,
data: Vec<D>
}
#[derive(Debug, Clone)]
struct BASKET{
cols: RefCell<Vec<COL>>
}
impl std::ops::Index<String> for BASKET {
type Output = COL;
fn index(&self, index: String) -> &Self::Output {
let mut i = 0;
for col in self.cols.clone().into_inner(){
if col.title == index{
println!("ok");
break;
}
i += 1;
}
// below warns: cannot return value referencing temporary value, how to avoid it?
self.cols.borrow().get(i).unwrap()
}
}
fn main() {
}
but the new problem cames,
it warns: lifetime parameters or bounds on type Output do not match the trait declaration
revised code:
use std::cell::RefCell;
use std::cell::Ref;
#[derive(Debug, Clone)]
enum D{
S(String),
F(f64)
}
#[derive(Debug, Clone)]
struct COL {
title: String,
data: Vec<D>
}
#[derive(Debug, Clone)]
struct BASKET{
cols: RefCell<Vec<COL>>
}
impl std::ops::Index<String> for BASKET {
//below warning: lifetime parameters or bounds on type `Output` do not match the trait declaration
type Output<'a> = Ref<'a, COL>;
fn index(&self, index: String) -> &Self::Output {
// let a = *self.borrow();
let b =Ref::filter_map(self.cols.borrow(),
|v|v.get(
v.iter().position(|k|k.title==index).unwrap()
)
).unwrap();
&b
}
}
fn main() {
}
Ah, sorry for not pointing this out before.
As far as I can tell, you cannot use the Index trait to do what you want. You'll have to make an accessor function, like fn get(&self, idx: usize) -> Ref<'_, COL>.