【问题标题】:How to print full struct path in Debug output?如何在调试输出中打印完整的结构路径?
【发布时间】:2021-11-05 11:36:39
【问题描述】:

我有mymod.rs:

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

还有main.rs:

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

输出是:

mystruct {
    x: 10,                                                    
}

我可以让它显示以下文字吗:

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

?

【问题讨论】:

  • 不是你想要的,但要注意dbg!存在

标签: struct rust println


【解决方案1】:

为了对结构的格式进行任何更改,您必须手动实现Debug 而不是使用#[derive(Debug)]。这是一个产生你想要的输出的实现:

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

可能还有一个库为Debug 提供了一个备用派生宏,可以配置为以这种方式打印类型名称,但我碰巧不知道。

顺便说一句,我注意到你有mymod::mymod。这不是构造 Rust 代码的常用方法。当您编写mod mymod; 时,它本身 会创建一个模块。模块文件中通常不应包含mod mymod { ... };这将创建 两个 级别的具有相同名称的模块。将 mod mymod; 用于单独的文件或将 mod mymod { ... } 用于内联在同一文件中的模块 - 不要同时使用两者,因为它是多余的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2021-06-11
    • 2014-12-28
    • 2021-02-12
    • 2011-07-04
    • 2020-12-19
    • 2012-04-19
    相关资源
    最近更新 更多