//! Comprehensive Struct Method Examples in Rust
#[derive(Debug, Clone, PartialEq)]
pub struct Circle {
radius: f64,
color: String,
}
impl Circle {
// Constructor method
pub fn new(radius: f64) -> Self {
Circle {
radius,
color: String::from("red"),
}
}
// Getter method
pub fn radius(&self) -> f64 {
self.radius
}
// Setter method
pub fn set_radius(&mut self, radius: f64) {
self.radius = radius;
}
// Instance method with immutable reference
pub fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
// Method taking ownership
pub fn consume(self) -> String {
format!("Consumed circle with radius {}", self.radius)
}
// Associated function (no self parameter)
pub fn default() -> Self {
Circle::new(1.0)
}
}
// Builder pattern implementation
pub struct CircleBuilder {
radius: Option<f64>,
color: Option<String>,
}
impl CircleBuilder {
pub fn new() -> Self {
CircleBuilder {
radius: None,
color: None,
}
}
pub fn radius(mut self, radius: f64) -> Self {
self.radius = Some(radius);
self
}
pub fn color(mut self, color: &str) -> Self {
self.color = Some(color.to_string());
self
}
pub fn build(self) -> Circle {
Circle {
radius: self.radius.unwrap_or(1.0),
color: self.color.unwrap_or_else(|| "blue".to_string()),
}
}
}
pub fn demonstrate_struct_methods() {
println!("=== BASIC STRUCT USAGE ===");
let mut circle = Circle::new(2.5);
println!("Original circle: {:?}", circle);
println!("Area: {:.2}", circle.area());
circle.set_radius(3.0);
println!("Modified radius: {}", circle.radius());
println!("\n=== BUILDER PATTERN ===");
let custom = CircleBuilder::new()
.radius(5.0)
.color("green")
.build();
println!("Built circle: {:?}", custom);
println!("\n=== OWNERSHIP DEMO ===");
let message = circle.consume();
println!("{}", message);
// circle is now moved and can't be used
println!("\n=== DEFAULT IMPLEMENTATION ===");
let default = Circle::default();
println!("Default circle: {:?}", default);
}
// Remember to add to src/menu_items/mod.rs:
// pub mod struct_methods;