2

I have mymod.rs:

pub mod mymod {
    #[derive(Debug)]
    pub struct mystruct {                          
        pub x: i32,
    }
}

And main.rs:

mod mymod;
use mymod::mymod::mystruct;
fn main() {
    let x = mystruct { x: 10 };
    println!("{:#?}", x);
}

Output is:

mystruct {
    x: 10,                                                    
}

Can I make it display the following text:

mymod::mymod::mystruct {
    x: 10,                                                    
}

?

kmdreko
  • 42,554
  • 6
  • 57
  • 106

1 Answers1

2

In order to make any changes at all to how a struct is formatted, you must manually implement Debug instead of using #[derive(Debug)]. Here's an implementation which produces the output you want:

pub mod mymod {
    use std::fmt;

    pub struct mystruct {                          
        pub x: i32,
    }
    
    impl fmt::Debug for mystruct {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct(std::any::type_name::<Self>())
                .field("x", &self.x)
                .finish()
        }
    }
}

Playground

There might also be a library that offers an alternate derive macro for Debug that could be configured to print the type name this way, but I don't happen to know of one.

By the way, I notice you have mymod::mymod. This isn't a usual way to structure Rust code; when you write mod mymod;, that itself creates a module. The module's file should not usually contain mod mymod { ... } inside it; that's creating two levels of modules with the same name. Either use mod mymod; for a separate file or mod mymod { ... } for a module that's inline in the same file — don't use both, as it's redundant.

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108