Visibility in Rust
pub(crate) and private fields are how a module keeps its invariants.
mod counter {
pub struct Counter {
count: u32,
pub(crate) label: String,
}
impl Counter {
pub fn new(label: &str) -> Self {
Counter { count: 0, label: label.to_string() }
}
pub fn bump(&mut self) -> u32 {
self.count += 1;
self.count
}
pub fn count(&self) -> u32 {
self.count
}
}
}
fn main() {
let mut c = counter::Counter::new("stars");
c.bump();
c.bump();
println!("{} = {}", c.label, c.count());
}
How it works
pub(crate)is visible in this crate but not outside it.- Private fields force construction through a constructor.
- Accessors keep the internals free to change.
Keywords and builtins used here
CounterSelfStringbumpcountcratefnimpllabelletmainmodmutnewpubselfstrstructu32
The run, in numbers
- Lines
- 28
- Characters to type
- 403
- Tokens
- 138
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 83 seconds.
Step 3 of 3 in Modules & visibility, step 3 of 12 in Modules, tests & macros.