I have been experimenting with Rust, and am quite happy with it. Unfortunately I have been banging my head against a wall now, and don't get why the below code would give an error.
I would expect that it's ok to have a reference to a Category in the item, but somehow it won't let me do that and return the Data object without complaining. It says that I return a value referencing data owned by the current function, but I would think that all data and references are moved/put in the resulting Data object, so there is no problem. But apparently I'm too much of a newbie in Rust. Took me a few hours, but every time I get to the same error in the end. Anybody a clue?
struct Data<'a> {
categories:Vec<Category>,
items:Vec<Item<'a>>
}
struct Category
{
id:String,
}
struct Item<'a>
{
id:String,
category:&'a Category,
}
struct Mapper {}
impl Mapper {
pub fn map() -> Data<'static>
{
let mut categories = Vec::<Category>::new();
categories.push(Category{ id:"cat1".to_string()});
categories.push(Category{ id:"cat2".to_string()});
let mut items = Vec::<Item>::new();
items.push(Item{ id:"item1".to_string(), category:categories.first().unwrap()});
items.push(Item{ id:"item2".to_string(), category:categories.last().unwrap()});
return Data { items, categories};
}
}
Error:
error[E0515]: cannot return value referencing local variable `categories`
--> src/SimpleTest.rs:30:16
|
27 | items.push(Item{ id:"item1".to_string(), category:categories.first().unwrap()});
| ------------------ `categories` is borrowed here
...
30 | return Data { items, categories};
| ^^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function