A struct field is one piece of data stored in a Rust struct. A named struct gives each field a name and a type; a tuple struct lists types without field names. You access a named field with a dot and its name, or a tuple field by position, such as `.1`. section 4.1.1
Give every field a value
`Country` has `population`, `capital`, and `leader_name` fields. Creating a `Country` requires a value for each one. If a variable has the same name as its field, `population` can stand in for `population: population`. section 4.1.1
Making a struct `pub` does not make its fields public. Add `pub` to each field that users should access. The same rule applies to tuple structs: `pub Email(String)` exposes the type but not its `.0` field; `pub Email(pub String)` exposes both. Keeping a field private lets a public constructor choose its value instead. section 14.1.2
mod print_things {
#[derive(Debug)]
pub struct Billy { #1
name: String,
pub times_to_print: u32,
}
impl Billy {
pub fn new(times_to_print: u32) -> Self { #2
Self {
name: "Billy".to_string(), #3
times_to_print,
}
}
pub fn print_billy(&self) {
for _ in 0..self.times_to_print {
println!("{}", self.name);
}
}
}
}
fn main() {
use print_things::*;
let my_billy = Billy::new(3); #4
my_billy.print_billy();
}
This example keeps `name` private, makes `times_to_print` public, and uses `new` to set the private field. section 14.1.2
One easy terminology mix-up: Rust also calls `#[derive(Debug)]` an attribute. That is a compiler-interpreted annotation, not a struct field. section 13.1.5

























