Reputation: 85
I am using {:?}
to print the value of a Breakfast
struct. It includes the private field seasonal_fruit
. Why I am able to print it with 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()
}
Upvotes: 2
Views: 916
Reputation: 431469
Why shouldn't it include private fields? When you debug things, you usually want to have access to as much information as possible. When you connect to the running process with a debugger, you have access to the same information, for example.
If you are actually asking how can it access private fields, then that's because the implementation of the Debug
trait for this struct is located in a scope that has access to the private fields of the struct (in the same module, in this case).
If you are actually asking how to prevent it from showing certain fields, then you can implement Debug
yourself for a type and control exactly what is included. This often uses methods like Formatter::debug_struct
to produce nicely formatted output.
See also:
Upvotes: 2