簡體   English   中英

特質實現的Rust自動類型推斷

[英]Rust automatic type inference on trait implementation

我不太了解下面的代碼有什么問題。 反正不清楚。 我曾經用一生來對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()]);
}

您需要將特征更改回:

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

據我了解 ,如果您放棄所有生命周期,生命周期省略將產生:

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

也就是說,您返回屬於objectString的切片。 但是,您希望結果來自input ,這不是默認規則將給出的結果。

編輯

建議更改為

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

說您的對象輸入具有相同的生存期。 結果生存期也將是'a (根據省略規則),因此返回輸入將適合生存期。 如果這對您的情況有意義,並且您要進行此更改,則會收到錯誤消息:

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

因為現在您的特征和該特征的實現不再匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM