作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 {:?}
打印 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
这样的方法。产生格式良好的输出。
也可以看看:
关于rust - 为什么 Debug 格式化程序会公开私有(private)结构字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68717395/
我是一名优秀的程序员,十分优秀!