Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import types inside of macros?

Tags:

macros

rust

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?

like image 935
Roman A. Taycher Avatar asked Dec 19 '25 13:12

Roman A. Taycher


1 Answers

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

like image 174
Lukas Kalbertodt Avatar answered Dec 21 '25 04:12

Lukas Kalbertodt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!