我正在处理一种不能像这样touch 的特征(最小化):
// The associated version
trait Testable {
type T;
fn test_it(&self, x: Self::T) -> bool;
}
然后我试着用,比方说,i32
:
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)为什么要编译通用版本?这两个版本之间有什么深层次的区别吗?