Use-ing only a trait not a derive with the same name

For my derive_more crate I'd like to use only the the Debug trait, but not the Debug derive. Because importing the derive would conflict with my own Debug derive that the trait creates. I cannot figure out a way to do this though, because this will always use both the trait and the derive:

pub use core::fmt::Debug

Is there any way to work around that? Or would this require language changes?

You could abuse the prioritization of explicit imports and items over glob imports. Example (this is the opposite of what you asked for, overriding the trait, just because that's easier to demonstrate).

// would be your derive macro crate
mod imp {
    pub trait Debug {}
}


mod namespace_gimmick {
    pub use std::fmt::*;
    pub use super::imp::Debug;
}
pub use namespace_gimmick::Debug as NewDebug;


// demonstrate that both were imported:
impl NewDebug for () {}
#[derive(NewDebug)]
struct Foo;

Since glob imports can be fragile, you'd want to do this in modules strictly dedicated to the purpose.

You could rename it as you use it?

use core::fmt::Debug as _;

will bring the trait into scope but not name it.

use core::fmt::Debug as CoreDebug;

will bring it into scope with a different name.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.