你能从特征中实现的另一个特征静态方法调用由类型实现的特征静态方法吗?例如:
trait SqlTable {
fn table_name() -> String;
fn load(id: i32) -> Something {
...
Self::table_name() // <-- this is not right
...
}
}
感谢 Chris 和 Arjan(见下面的评论/答案)
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") }
}
最佳答案
您必须将 Self 更改为 SqlTable:
trait SqlTable {
fn table_name() -> String;
fn load(id: i32) -> Self {
...
SqlTable::table_name() // <-- this is not right
...
}
}
静态方法总是在像 SomeTrait::some_method() 这样的特征上被调用。错误 #6894涵盖了这个问题。
关于static - 从另一个静态方法调用 trait 静态方法 (rust),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24541074/