Is it okay to `use` in derive proc macros?

I have a proc macro I'm building, but it's getting pretty tedious to write explicitly. I have to specify e.g. crate::mod::Trait every time I want to refer to Trait and have to use <T as crate::mod::Trait>::fn(t, ...) to access fn from that trait. Is it fine on all cases to just use crate::mod::Trait; inside of a fn implementation of a derive proc macro?

You should technically usually do ::crate_name::Trait anywhere you use the path, in case a user imports another module with that name into scope.

uses are fine as long as they're in a scope that's hidden from the user of the macro. For example if you're generating a function body and there's no code being passed directly from the user in the function I think it should be fine to do a use there.

On the other hand if the user is passing a block of code into the proc macro then it's entirely possible that any use would inadvertently change the behavior of that block.

You can also just define some utility functions to create the full paths you need since you're already using a proc macro though.

3 Likes