gpt4 book ai didi

rust - 为什么 Debug 格式化程序会公开私有(private)结构字段?

转载 作者:行者123 更新时间:2023-12-04 07:16:44 25 4
gpt4 key购买 nike

我正在使用 {:?}打印 Breakfast 的值结构。它包括私有(private)字段 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()
}

最佳答案

为什么不应该包含私有(private)字段?当您调试事物时,您通常希望能够访问尽可能多的信息。例如,当您使用调试器连接到正在运行的进程时,您可以访问相同的信息。
如果你真的问 如何它可以访问私有(private)字段,那是因为 Debug 的实现此结构的特征位于可以访问结构的私有(private)字段的范围内(在本例中位于同一模块中)。
如果您实际上是在问如何 防止它从显示某些字段,然后你可以实现Debug自己获取类型并准确控制包含的内容。这通常使用像 Formatter::debug_struct 这样的方法。产生格式良好的输出。
也可以看看:

  • What exactly does '#[derive(Debug)]' mean in Rust?
  • 关于rust - 为什么 Debug 格式化程序会公开私有(private)结构字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68717395/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com