0

我收到此错误 - “由于要求冲突,无法推断自动强制的适当生命周期”。但是,我试图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 () {
}
4

1 回答 1

2

此函数签名承诺返回对 Job 的引用。

fn start_duty<'dutylife> (duty: &'dutylife Duty) -> &'dutylife Job

您可能想要做的是返回Job包含对 a 的引用的 a Duty

fn start_duty<'dutylife> (duty: &'dutylife Duty) -> Job<'dutylife> {

    Job {
        duty: duty,
        output: "".to_string(),
        success: JobNotDone
    }

}

还有另一个错误,代码试图返回对此函数中创建的作业的引用。我也修复了这个问题,代码现在可以编译了。让我知道这是否是你想要做的。

编辑:回应“工作只能在职责的一生中存在;当职责消失时,工作也应该存在。” 部分。

这不能以您尝试的方式完成,因为 Job 对象将在函数结束时不存在,并且对它的任何引用都将变为无效。

最简单的方法是让一个Duty拥有Job(s)在它上面工作(通过给它一个Option<Job>Option<Vec<Job>>字段)。这是单一所有者的方法。多个所有者要复杂得多,并且会涉及引用计数指针或原始指针。

于 2014-06-08T19:02:35.070 回答