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
...
}
}
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") }
}
You have to change Self to SqlTable:
trait SqlTable {
fn table_name() -> String;
fn load(id: i32) -> Self {
...
SqlTable::table_name() // <-- this is not right
...
}
}
Static methods are always called on a trait like SomeTrait::some_method(). Bug #6894 covers this issue.
Ant Manelope
- 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.
来源:https://stackoverflow.com/questions/24541074/calling-trait-static-method-from-another-static-method-rust