Rust
Beginner
1 min read
Struct Visibility and Encapsulation
Example
mod config {
#[derive(Debug)]
pub struct ServerConfig {
host: String, // private
pub port: u16, // public
max_connections: usize, // private
timeout_secs: u64, // private
}
impl ServerConfig {
// Only way to construct from outside the module
pub fn new(host: &str, port: u16) -> Self {
ServerConfig {
host: host.to_string(),
port,
max_connections: 100,
timeout_secs: 30,
}
}
pub fn host(&self) -> &str { &self.host }
pub fn max_connections(&self) -> usize { self.max_connections }
pub fn with_max_connections(mut self, n: usize) -> Self {
self.max_connections = n;
self
}
pub fn with_timeout(mut self, secs: u64) -> Self {
self.timeout_secs = secs;
self
}
}
}
fn main() {
// Builder-style construction using method chaining
let cfg = config::ServerConfig::new("127.0.0.1", 8080)
.with_max_connections(500)
.with_timeout(60);
println!("host = {}", cfg.host());
println!("port = {}", cfg.port); // pub field — direct access ok
println!("max connections = {}", cfg.max_connections());
// cfg.host = "x".to_string(); // compile error: field is private
}