Calling trait static method from another static method (rust)

谁说胖子不能爱 提交于 2019-11-30 18:38:06

问题


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") }
}

回答1:


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.




回答2:


  • 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 it None::<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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!