static - 从另一个静态方法调用 trait 静态方法 (rust)

标签 static rust traits

你能从特征中实现的另一个特征静态方法调用由类型实现的特征静态方法吗?例如:

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/

相关文章:

c++ - 一个编译单元中的静态初始化

c++ - MSVC 如何优化静态变量的使用?

string - 在忽略大小写的情况下比较字符串的有效方法是什么?

rust - Rust 将借来的值保存在集合中的方法是什么?

php - Rust regex replace_all 比 PHP regex preg_replace_callback 慢,如何优化?

jakarta-ee - JPA 实体静态记录器

C++ 静态运算符重载

oop - 如何动态生成用于特征的值?

C++ 特征问题

c++ - 跨 C++0x 编译器的 lambda 特征不一致