Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use a trait method without bringing it into scope? [duplicate]

Tags:

scope

rust

traits

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

like image 544
zombiesauce Avatar asked Jan 20 '26 06:01

zombiesauce


1 Answers

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);
like image 130
Netwave Avatar answered Jan 23 '26 07:01

Netwave