[英]How do I provide type parameters to trait functions that don't take self?
这不会编译:
pub trait TheTrait<T> {
pub fn without_self() -> T;
pub fn with_self(&self) -> T {
TheTrait::without_self()
}
}
因为编译器无法找出TheTrait::without_self()
的类型参数。 我想要类似TheTrait<T>::without_self()
,但是找不到有效的语法。 我如何提供类型参数给without_self
?
编者注:从Rust 1.0开始,此答案已过时
如果函数签名中没有Self
或self
,则至少在实现UFCS之前,它是不可调用的。 现在,您可以将Option<Self>
作为参数,并使用None::<Self>
作为解决方法。
pub trait TheTrait<T> {
fn without_self(Option<Self>) -> T;
fn with_self(&self) -> T {
TheTrait::without_self(None::<Self>)
}
}
我想要类似
TheTrait<T>::without_self()
,但是找不到有效的语法。 我如何提供类型参数给without_self
?
如今,使用完全合格的语法,您可以像这样:
<T as TheTrait>::without_self()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.