繁体   English   中英

由于需求冲突,无法推断出自动强制的适当寿命

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM