[英]Calling trait static method from another static method (rust)
Can you call a trait static method implemented by types from another trait static method implemented in the trait?你能从特征中实现的另一个特征 static 方法中调用类型实现的特征 static 方法吗? 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)感谢 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") }
}
You have to change Self to SqlTable: 你必须将Self改为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(). 静态方法总是在像SomeTrait :: some_method()这样的特性上调用。 Bug #6894 covers this issue. 错误#6894涵盖了这个问题。
SomeTrait::some_method()
. 静态方法总是在像SomeTrait::some_method()
这样的特性上调用。 _: Option<Self>
and pass it None::<T>
. 直到UFCS出现的标准解决方法是采用参数_: Option<Self>
并将其传递给None::<T>
。 See original question for code that (as of today) compiles. 查看(截至今天)编译的代码的原始问题。
This works without any workarounds with current Rust (verified with 1.65.0):这适用于当前 Rust(已通过 1.65.0 验证)的任何解决方法:
trait Trait {
fn x() -> i32 {
1
}
}
struct Struct {
y: i32,
}
impl Struct {
fn new(y: i32) -> Self {
Self { y }
}
fn f(self) -> i32 {
Self::x() + self.y
}
}
impl Trait for Struct {}
fn main() {
assert_eq!(Struct::new(1).f(), 2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.