Skip to content

Compiler error: returns a value referencing data owned by the current function #1239

Answered by hecrj
tareksalem asked this question in Q&A
Discussion options

You must be logged in to vote

You are calling view of an item.clone() inside a for loop and assigning it to content. The cloned item is very short-lived but the content, which may borrow from the cloned item, needs to live as much as the row! This isn't a valid Rust program!

The solution here is to avoid cloning and actually borrow from self.data:

pub fn view(&mut self) -> Row<Message> {
    let mut row = Row::new();

    for item in &mut self.data {
        row = row.push(item.view());
    }

    row
}

You can also take a more functional approach with iter_mut and fold:

pub fn view(&mut self) -> Row<Message> {
    self.data
        .iter_mut()
        .fold(Row::new(), |row, item| row.push(item.view()))
}

Hope that h…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@tareksalem
Comment options

@hecrj
Comment options

hecrj Feb 9, 2022
Maintainer

Answer selected by hecrj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants