[英]cannot infer an appropriate lifetime for automatic coercion due to conflicting requirements
我收到此錯誤-“由於需求沖突,無法推斷出自動強制的適當壽命”。 但是,我嘗試了明確執行start_duty
要求。
error.rs:45:1: 55:2 note: consider using an explicit lifetime parameter as shown: fn start_duty<'dutylife>(duty: &'dutylife Duty) -> &'dutylife Job<'dutylife>
error.rs:45 fn start_duty<'dutylife> (duty: &'dutylife Duty) -> &'dutylife Job {
error.rs:46
error.rs:47 let j : Job = Job {
error.rs:48 duty: duty,
error.rs:49 output: "".to_string(),
error.rs:50 success: JobNotDone
...
error.rs:48:15: 48:19 error: cannot infer an appropriate lifetime for automatic coercion due to conflicting requirements
error.rs:48 duty: duty,
^~~~
error: aborting due to previous error
我的代碼有點過時的版本會導致錯誤。 從概念上講,我試圖做的是生成一個引用職責的新Job。 工作只能在職責的整個生命周期中存在; 當職責消失時,工作也應如此。
enum Source {
Nothing, // Nothing
Git(String, String), // reponame, refname
Hg(String, String), // reponame, csid
Url(String) // curl down what's here
}
enum JobResult {
JobNotDone,
JobSuccess,
JobFailure,
JobError
}
/*
Jobs
Jobs are always attached to the Duty that spawned them; there can be
no Job without the duty. So we take a lifetime param of the duty reference
*/
struct Job<'r> {
duty: &'r Duty, // pointer back to
output: String, // no output = ""
success: JobResult
}
enum Action {
BashScript(String)
}
struct Duty {
name: String,
source: Source,
action: Action,
comment: Option<String>
}
struct Agent<'r> {
hostname : String,
uid : u64,
job : Option<Job<'r>>, // mutable, agents
}
// returns new Job, but with duty referenced.
fn start_duty<'dutylife> (duty: &'dutylife Duty) -> &'dutylife Job {
let j : Job = Job {
duty: duty,
output: "".to_string(),
success: JobNotDone
};
return &j;
}
fn main () {
}
此功能簽名承諾返回對作業的引用。
fn start_duty<'dutylife> (duty: &'dutylife Duty) -> &'dutylife Job
您可能想做的是返回一個包含對Duty
的引用的Job
:
fn start_duty<'dutylife> (duty: &'dutylife Duty) -> Job<'dutylife> {
Job {
duty: duty,
output: "".to_string(),
success: JobNotDone
}
}
還有另一個錯誤,代碼試圖返回對該函數中創建的Job的引用。 我也修復了該問題,現在可以編譯代碼。 讓我知道您是否正在嘗試這樣做。
編輯:回應“工作只能在職責的整個生命周期中存在;當職責消失時,工作也應該存在。” 部分。
這無法用您嘗試的方式完成,因為當函數結束時,Job對象將不復存在,並且對其的任何引用都將變為無效。
最簡單的方法是讓Duty
擁有在其上Job
的工作(通過給它一個Option<Job>
或Option<Vec<Job>>
字段)。 這是單一所有者的方法。 多個所有者要復雜得多,並且會涉及引用計數的指針或原始指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.