I am venturing to the world of lifetimes and structs that contain mutable structs:
enum Resources {
Food,
Wood,
Tools,
Ore,
Metal,
}
struct ResourceEntry {
resource: Resources,
amount: i32,
}
impl ResourceEntry {
fn new(resource: Resources, amount: i32) -> ResourceEntry {
ResourceEntry {
resource: resource,
amount: amount,
}
}
}
trait Agent {
fn new<'a>(&'a mut Vec<ResourceEntry>) -> Self;
}
struct Miner<'a> {
inventory: &'a mut Vec<ResourceEntry>,
}
impl<'a> Agent for Miner<'a> {
fn new(starting_resource: &'a mut Vec<ResourceEntry>) -> Miner {
Miner { inventory: starting_resource }
}
}
fn main() {
let mut resource = ResourceEntry::new(Resources::Food, 3);
let mut vec = vec![resource];
let miner: Miner = Miner::new(vec);
miner.perform();
}
I get the following error
error[E0308]: method not compatible with trait
--> other.rs:47:5
|
47 | fn new(starting_resource: &'a mut Vec<ResourceEntry>) -> Miner
| ^ lifetime mismatch
|
= note: expected type `fn(&'a mut std::vec::Vec<ResourceEntry>) -> Miner<'a>`
= note: found type `fn(&'a mut std::vec::Vec<ResourceEntry>) -> Miner<'a>`
note: the lifetime 'a as defined on the block at 48:4...
--> other.rs:48:5
|
48 | {
| ^
note: ...does not necessarily outlive the lifetime 'a as defined on the block at 48:4
--> other.rs:48:5
|
48 | {
| ^
help: consider using an explicit lifetime parameter as shown: fn new(starting_resource: &'a mut Vec<ResourceEntry>) -> Miner
--> other.rs:47:5
|
47 | fn new(starting_resource: &'a mut Vec<ResourceEntry>) -> Miner
| ^
I can't for the life of me wrap my head around what the compiler is telling me. The error messages are saying to do exactly what I am doing. Maybe I'm misunderstanding but it's saying that the lifetime of a
doesn't match the lifetime of a
? I thought I had a pretty good grasp of borrowing and ownership but the use of explicit lifetimes and objects that reference other objects has me confused.
Is the problem
fn new<'a>(&'a mut Vec) -> Self;
I had trouble with getting new to accept a lifetime correctly and I'm wondering if this isn't something you should do in Rust?