[英]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];
}
也就是说,您返回属于object的String
的切片。 但是,您希望结果来自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.