我正在处理一种无法像这样(缩小)触摸的特性:
// The associated version
trait Testable {
type T;
fn test_it(&self, x: Self::T) -> bool;
}
然后我会尝试用i32等类型的数据进行impl
操作:
impl Testable for i32 {
type T = &str;
fn test_it(&self, x: Self::T) -> bool {
x.is_empty()
}
}
然而,我遇到了编译器错误:
type T = &str;
^ explicit lifetime name needed here
相关联的类型Self::T
只是方法test_it
的输入参数。为什么编译器要求我提供生命周期注释?
请注意,如果我将T
更改为通用类型,例如:
// The generic version
trait Testable<T> {
fn test_it(&self, x: T) -> bool;
}
impl Testable<&str> for i32 {
fn test_it(&self, x: &str) -> bool {
x.is_empty()
}
}
这次代码编译无误。
问题在于:
(1) 为什么我必须在关联版本中提供生命周期注解,因为该类型仅出现在输入参数一侧?
(2) 为什么泛型版本被编译了?这两个版本之间是否存在深层区别?
rustc --explain E0637
吗?这是绝对不被允许的。 - cafce25T =&str
一起工作,而在第二个版本中,您实际上可以放置生命周期注释,编译器也可以为您确定。 - isaactfa