Compiler error: returns a value referencing data owned by the current function #1239
-
Hi, I am just new to iced and also new to rust at all, here is an example on what I want to do use iced::{Row, Element, Text};
#[derive(Clone)]
pub struct MarkData{
title: String,
description: String,
content: String,
image: String
}
enum Message{}
#[derive(Clone)]
pub struct MarkComponent{
data: MarkData
}
impl MarkComponent {
fn new(data: MarkData) -> Self {
Self {
data
}
}
pub fn view(&mut self) -> Row<Message> {
let mut row = Row::new();
row = row.push(
Text::new(&self.data.title).size(25)
);
row
}
}
#[derive(Clone)]
pub struct MarkComponents{
data: Vec<MarkComponent>,
}
impl MarkComponents {
pub fn new() -> Self {
let iter = (0..20).map(|a| MarkData {
title: format!("title {}", a),
description: format!("description {}", a),
content: format!("content {}", a),
image: format!("https://google.com")
});
Self {
data: Vec::from_iter(iter.map(|item| {
MarkComponent::new(item)
}))
}
}
pub fn view(&mut self) -> Row<Message> {
let mut row = Row::new();
for item in &self.data {
let content =
item.clone().view();
row = row.push( content );
}
return row;
}
} however this is not working because MarkComponents.view method panics with the following error
Thank you |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
You are calling The solution here is to avoid cloning and actually borrow from 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 pub fn view(&mut self) -> Row<Message> {
self.data
.iter_mut()
.fold(Row::new(), |row, item| row.push(item.view()))
} Hope that helps! |
Beta Was this translation helpful? Give feedback.
You are calling
view
of anitem.clone()
inside a for loop and assigning it tocontent
. The cloned item is very short-lived but thecontent
, which may borrow from the cloned item, needs to live as much as therow
! This isn't a valid Rust program!The solution here is to avoid cloning and actually borrow from
self.data
:You can also take a more functional approach with
iter_mut
andfold
:Hope that h…