简体   繁体   中英

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?

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 ;-)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM