我屏住了壽命和結構的世界包含可變結構:方法不與令人困惑的錯誤消息特質兼容
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();
}
我收到以下錯誤
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
| ^
我不能因爲我的生活圍繞着編譯器告訴我的東西。錯誤信息說明我正在做什麼。也許我是誤解,但是這是說a
的使用期限與a
的使用期限不符?我認爲我對借用和所有權有很好的把握,但使用明確的生命週期和引用其他對象的對象讓我感到困惑。
是問題
fn new<'a>(&'a mut Vec) -> Self;
我曾與獲得新的正確接受了一輩子的麻煩,我想知道,如果這不是你應該做鏽?
太棒了!就是這樣。我會確保報告錯誤。 正因爲如此,我確切知道發生了什麼事情,Miner Agent的實現不兼容,因爲特質Agent沒有與它關聯的生命週期。所以當它試圖在實現中編譯new時,它發現它有來自Agent :: new的生命週期,但是它是一個隨機的其他生命週期,因爲該生命週期不在輸出中,所以它無法計算出來。特質水平的生命週期允許您將impl塊中的生命週期與您的礦工生命週期相提並論。 – Erik
@Erik更新了更多文字。 – Shepmaster