Get warning:cannot return value referencing temporary value

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() {

}

You need to change the return type to Ref<'_, Self::Output> and use Ref::map to map the ref to the vector to a ref to the element.

1 Like

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>.

2 Likes

thanks for your help,

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.