Calling trait static method from another static method (rust)

后端 未结 2 898
北恋
北恋 2021-01-06 07:13

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_         


        
相关标签:
2条回答
  • 2021-01-06 08:14
    • 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.

    0 讨论(0)
  • 2021-01-06 08:19

    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.

    0 讨论(0)
提交回复
热议问题