1

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().

zombiesauce
  • 1,009
  • 1
  • 7
  • 22
  • 3
    `TraitName::trait_method (&some_obj)`? – Jmb Oct 18 '21 at 10:26
  • Well yeah, while that would work, that would break the whole dot chain. I was hoping a syntax similar to the one I showed would be applicable. – zombiesauce Oct 18 '21 at 10:29
  • Personally don't know of any way except of using fully qualified syntax. One workaround could be to limit the scope and import trait: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=550801a3b425ac51cedc320a66f78276 – Mihir Luthra Oct 18 '21 at 11:14

1 Answers1

2

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);
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • I already knew this is possible. However, when you're method chaining, this breaks the entire flow. At that point, it's just easier to just add a `use` and be done with it. This isn't a real issue anyways, I was just asking because I was curious. – zombiesauce Oct 18 '21 at 17:01
  • 1
    @VivekYadav, uhm, yes, it is not suitable to actually chain them. But I dont see the problem on using `use` really. – Netwave Oct 18 '21 at 17:04
  • 1
    None really, like i said, I was just curious, as I have been noticing some inconsistencies in Rust. I'm also thinking to ask a similar question but about the inconsistency in allowing variable shadowing, but not function name overloading (though both signify the same thing - similar task but done with a different data type). – zombiesauce Oct 18 '21 at 17:13