The use of use in Rust so far seems pretty simple - everything is already "imported" (in the sense that other languages use the word), use just brings them into scope.
However, for traits, this seemingly falls apart. To use a trait's methods on a struct, the said trait must be in scope.
So I thought, if the behavior of use be consistent, then there must be another, more verbose way of calling trait methods.
So I tried:
fn main() {
some_obj.TraitName::trait_method();
}
However this doesn't seem to compile. So is there a way to do this or is use inconsistent in this sense?
EDIT: TraitName is the full path of the trait, i.e some_obj.module_1::TraitName::trait_method().
You could use fully qualified syntax:
<Type as crate::mod::TraitName>::trait_method(object);
as example:
mod m {
pub trait Foo {
fn foo(&self) {}
}
impl<T> Foo for T {}
}
fn main() {
let x = 10u32;
<u32 as m::Foo>::foo(&x);
}
Playground
Or just let the compiler elide the types:
m::Foo::foo(&x);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With