【问题标题】:Rust automatic type inference on trait implementationRust 对 trait 实现的自动类型推断
【发布时间】:2014-12-08 02:00:37
【问题描述】:

我不太明白下面的代码有什么问题。反正也不是很清楚。我曾经用一生来参数化 Toto,但我想我会试一试终身推断。问题似乎与对 self 的引用有关。我得到编译器错误:

embedded_lifetimes.rs:11:5: 11:10 error: cannot infer an appropriate lifetime for automatic coercion due to conflicting requirements
embedded_lifetimes.rs:11     slice
                         ^~~~~
embedded_lifetimes.rs:10:3: 12:4 help: consider using an explicit lifetime parameter as shown: fn klax<'a>(&'a self, slice: &'a [String]) -> &[String]
embedded_lifetimes.rs:10   fn klax(&self, slice: &[String]) -> &[String] {
embedded_lifetimes.rs:11     slice
embedded_lifetimes.rs:12   }

对于以下代码:

#![feature(slicing_syntax)]

trait Toto {
  fn klax(&self, &[String]) -> &[String];
}

struct Tata;

impl Toto for Tata {
  fn klax(&self, slice: &[String]) -> &[String] {
    slice
  }
}

fn main() {
  let t = Tata;
  t.klax(&["myello".to_string()]);
}

【问题讨论】:

    标签: rust


    【解决方案1】:

    你需要将你的特质改回:

    trait Toto<'a> {
        fn klax(&self, &'a [String]) -> &'a [String];
    }
    

    As I understand it,如果你放弃所有生命周期,生命周期省略将产生:

    trait Toto<'a> {
        fn klax(&'a self, &[String]) -> &'a [String];
    }
    

    也就是说,您返回属于 objectStrings 切片。但是,您希望结果来自 输入,这不是默认规则所提供的。

    编辑

    建议更改为

    fn klax<'a>(&'a self, slice: &'a [String]) -> &[String]
    

    表示您的 objectinput 具有相同的生命周期。结果生命周期也将是'a(根据省略规则),因此返回输入将适合生命周期。如果这对您的情况有意义并且您要进行此更改,则会收到错误消息:

    method `klax` has an incompatible type for trait: expected concrete lifetime, found bound lifetime parameter
    

    因为现在你的 trait 和该 trait 的实现不再匹配。

    【讨论】:

    • 是的,我已经尝试过了并且遇到了那个错误:参数化 klax 的实现而不是 trait。您对推理的解释回答了我的问题。谢谢!
    猜你喜欢
    • 2015-08-07
    • 2010-09-29
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    相关资源
    最近更新 更多