从另一个静态方法(rust)调用特征静态方法 [英] Calling trait static method from another static method (rust)
本文介绍了从另一个静态方法(rust)调用特征静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你能从另一个在 trait 中实现的 trait 静态方法调用一个由类型实现的 trait 静态方法吗?例如:
Can you call a trait static method implemented by types from another trait static method implemented in the trait? For example:
trait SqlTable {
fn table_name() -> String;
fn load(id: i32) -> Something {
...
Self::table_name() // <-- this is not right
...
}
}
感谢 Chris 和 Arjan(请参阅下面的评论/答案)
This is now working thanks to Chris and Arjan (see comments/answers below)
fn main() {
let kiwibank = SqlTable::get_description(15,None::<Account>);
}
trait SqlTable {
fn table_name(_: Option<Self>) -> String;
fn get_description(id: i32, _: Option<Self>) -> String {
println!("Fetching from {} table", SqlTable::table_name(None::<Self>) );
String::from_str("dummy result")
}
}
struct Account {
id: i32,
name: String,
}
impl SqlTable for Account {
fn table_name(_: Option<Account>) -> String { String::from_str("account") }
}
推荐答案
- 是的,您可以从另一个特征静态方法[在特征中实现] 调用特征静态方法[由类型实现].
- 静态方法总是在像
SomeTrait::some_method()
这样的特征上被调用. - [a trait] 函数签名中没有 Self 或 self 的地方,目前是不可调用的.UFCS 出现之前的标准解决方法是采用参数
_: Option
并将其传递给None::
. - Yes, you can call a trait static method [implemented by types] from another trait static method [implemented in the trait].
- Static methods are always called on a trait like
SomeTrait::some_method()
. - Where there is no Self or self in [a trait] function signature, it is not callable at present. The standard workaround until UFCS comes is to take an argument
_: Option<Self>
and pass itNone::<T>
.
有关(截至今天)编译的代码的原始问题.
See original question for code that (as of today) compiles.
这篇关于从另一个静态方法(rust)调用特征静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文