Roman A. Taycher
Roman A. Taycher

Reputation: 19477

How do I import types inside of macros?

Are use-statements in the middle of functions allowed?

If so, how do I refer to the module (self? super? full path?)

If not, is importing a struct/enum and macro in the file where I'm calling the macro the only option?

Upvotes: 3

Views: 1341

Answers (2)

belst
belst

Reputation: 2525

You can simply use use inside a function. For example:

fn foo() {
    // do some other stuff
    use std::collections::HashMap; // use statement only valid
                                   // inside the current scope
    // use HashMap
}

use statements are always absolute to the crate root. You can make them relative to the current module like this: use self::submodule::Type

This is also documented in the Rust book.

Upvotes: 0

Lukas Kalbertodt
Lukas Kalbertodt

Reputation: 88526

Are use-statements in the middle of functions allowed?

Yes.

If so, how do I refer to the module (self? super? full path?)

[from comment] How do I refer to the module which the macro and type are defined in?

AFAIK, this is not really possible. The only hope is the special $crate meta-variable which refers to the crate the macro is defined in. Thus you can and have to specify the whole path of the type you want to refer to, like:

use $crate::path::to::MyType;

Note that this type has to be public to be accessible in other crates which use your macro! This means the type belongs to the public interface of your crate and changing its path is considered a breaking change. Since breaking changes should occur rather seldom, you won't have to change the path in the macro definition very often ;-)

Upvotes: 7

Related Questions