Macros that import/use modules define same name again

In the following example, even though I could import use core::marker::PhantomData; on the top level, I think it would be better if the implementation also could load them for me. So I don't have to import use core::marker::PhantomData; on all modules that use this macro. Imagine that instead of use core::marker::PhantomData;, there were lots of use stuff that should be imported over and over.

struct A<'a, T> {
    _data: &'a[T],
}

pub mod something {
    use core::marker::PhantomData;
    pub trait Something<'a, T>{
        fn use_phantom(&self, _p: PhantomData<T>);
    }
    
    pub trait Something2<'a, T>{
        fn use_phantom_2(&self, _p: PhantomData<T>);
    }
}


macro_rules! impl_something {
    ($struct_name:ident) => {
        use core::marker::PhantomData;
        impl<'a, T> something::Something<'a, T> for $struct_name<'a, T> {
            fn use_phantom(&self, p: PhantomData<T>) {
                todo!()
            }
        }
    };
}

macro_rules! impl_something2 {
    ($struct_name:ident) => {
        use core::marker::PhantomData;
        impl<'a, T> something::Something2<'a, T> for $struct_name<'a, T> {
            fn use_phantom_2(&self, p: PhantomData<T>) {
                todo!()
            }
        }
    };
}

impl_something!(A);
impl_something2!(A);

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=493d47d3c589b41dbaf5c30c1c17cd4b

Is it possible to re-import stuff on a macro for the trait implementation?

I thought of doing

use core::marker::PhantomData as PhantomData_$struct_name so it's unique per implementation. Is there a better way? Is such concatenation PhantomData_$struct_name even possible?

The usual solution is to use the fully-qualified name std::marker::PhantomData instead of importing it or relying on the import being present.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.