我收到此错误 - "由于要求冲突而无法推断自动强制的适当生命周期"。但是,我已尝试明确强制执行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
我的代码有点被淘汰的版本导致错误。从概念上讲,我要做的是生成一个引用职责的新工作。在职责的有效期内,工作只能 存在;当责任消失时,工作也应该如此。
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 () {
}
答案 0 :(得分:1)
此函数签名承诺返回对Job的引用。
fn start_duty<'dutylife> (duty: &'dutylife Duty) -> &'dutylife Job
您可能想要做的是返回包含对Job
的引用的Duty
:
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>>
字段)。这是一个单一的所有者方法。多个所有者明显更复杂,并且涉及引用计数指针或原始指针。