[英]Can a static function in a trait call another static function in same trait?
Can a static function in a trait call another static function in same trait? 特性中的静态函数可以调用相同特性中的另一个静态函数吗? Suppose I have a trait below:
假设我具有以下特征:
trait Test {
fn prt() {
println!("ok");
}
fn test() {
Test::prt();
}
}
That doesn't work. 那不行 Code just can't compile here.
代码只是不能在这里编译。
Also, there is no type for me to use fully qualified syntax like <T as Test>::Test
. 另外,我没有类型可以使用完全限定的语法,例如
<T as Test>::Test
。 Is there another way to do this? 还有另一种方法吗?
Inside a trait definition, you can use Self
to refer to the type which implements the trait. 在特征定义中,您可以使用
Self
来引用实现特征的类型。 For you, that would look like: 对于您来说,它看起来像:
trait Test {
fn prt() {
println!("ok");
}
fn test() {
Self::prt();
}
}
There really is no such method as Test::test
because its body is always defined by implementations of the trait. 实际上没有
Test::test
这样的方法,因为它的主体始终由trait的实现定义。 It just so happens that implementors will get that body by default if they don't provide their own. 碰巧的是,如果实现者不提供自己的实体,则默认情况下将获得该主体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.