简体   繁体   中英

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. The issue seems to be with the reference to self.I get the compiler error:

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 . However, you want the result to come from the input , which isn't what the default rules will give.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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