简体   繁体   English

特质实现的Rust自动类型推断

[英]Rust automatic type inference on trait implementation

I don't really understand what is the issue with my code below. 我不太了解下面的代码有什么问题。 Not clearly anyways. 反正不清楚。 I used to parameterize Toto with a lifetime but I figured I'd give lifetime inference a shot. 我曾经用一生来对Toto进行参数化,但我想我会给出一生的推断。 The issue seems to be with the reference to self.I get the compiler error: 问题似乎与对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   }

For the following code: 对于以下代码:

#![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()]);
}

You'll need to change your trait back to: 您需要将特征更改回:

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

As I understand it , if you leave off all the lifetimes, lifetime elision will yield: 据我了解 ,如果您放弃所有生命周期,生命周期省略将产生:

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

That is, you return a slice of String s that belong to the object . 也就是说,您返回属于objectString的切片。 However, you want the result to come from the input , which isn't what the default rules will give. 但是,您希望结果来自input ,这不是默认规则将给出的结果。

Edit 编辑

The suggested change to 建议更改为

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

Says that your object and the input have the same lifetime. 说您的对象输入具有相同的生存期。 The result lifetime would also be 'a (by the elision rules), and so returning the input would fit the lifetime. 结果生存期也将是'a (根据省略规则),因此返回输入将适合生存期。 If this made sense for your case and you were to make this change, you'd get the error: 如果这对您的情况有意义,并且您要进行此更改,则会收到错误消息:

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

Because now your trait and implementation of that trait no longer match. 因为现在您的特征和该特征的实现不再匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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