为什么调试格式化程序公开私有结构字段?

Why does the Debug formatter expose private struct fields?

我正在使用 {:?} 打印 Breakfast 结构的值。它包括私有字段 seasonal_fruit。为什么我可以使用 println!?

打印它
mod back_of_house {
    #[derive(Debug)]

    pub struct Breakfast {
        pub toast: String,
        seasonal_fruit: String, // NOT PUB !!!
    }

    impl Breakfast {
        pub fn summer(toast: &str) -> Breakfast {
            Breakfast {
                toast: String::from(toast),
                seasonal_fruit: String::from("Peaches"),
            }
        }
    }
}

pub fn eat_at_restaurant() {
    // Order a breakfast in the summer with Rye toast
    let mut meal = back_of_house::Breakfast::summer("Rye");

    // Change our mind about what bread we'd like
    meal.toast = String::from("Wheat");

    println!("I'd like {} toast please", meal.toast);

    println!("I'd like {:?} toast please", meal);
}

fn main() {
    eat_at_restaurant()
}

为什么不应该包含私有字段?当您 调试 东西时,您通常希望能够访问尽可能多的信息。例如,当您使用调试器连接到 运行 进程时,您可以访问相同的信息。

如果您实际上是在问 它如何 访问私有字段,那是因为此结构的 Debug 特征的实现位于具有访问结构的私有字段(在本例中,在同一模块中)。

如果您实际上是在询问如何防止它显示某些字段,那么您可以自己实现Debug 类型并准确控制包含的内容。这通常使用 Formatter::debug_struct 之类的方法来生成格式良好的输出。

另请参阅: