Skip to content
Snippets Groups Projects
Commit ed68c142 authored by Michael Hauspie's avatar Michael Hauspie
Browse files

Initial commit

parents
No related branches found
No related tags found
No related merge requests found
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "bike"
version = "0.1.0"
[package]
name = "bike"
version = "0.1.0"
edition = "2024"
[dependencies]
An example of Builder pattern in rust
# Example usage
```rust
let builder = Bike::builder();
let bike = builder.with_brakes(Brake::Disk)
.with_transmission(Transmission::GearHub)
.with_wheels(Wheel::Small)
.build();
println!("{bike:#?}");
bike.ride();
```
#![doc = include_str!("../README.md")]
#[derive(Debug)]
pub enum Brake {
Disk,
Pads
}
#[derive(Debug)]
pub enum Wheel {
Large,
Small,
}
#[derive(Debug)]
pub enum Transmission {
Standard,
GearHub,
}
#[derive(Debug)]
pub struct Bike {
brakes: Brake,
wheels: Wheel,
transmission: Transmission,
}
impl Bike {
/// Ride your bike!
pub fn ride(&self) {
println!("I am riding {:?}", self);
}
/// Create a new builder to start a bike configuration
pub fn builder() -> BikeBuilder {
BikeBuilder::default()
}
}
#[derive(Default,Debug)]
/// A bike builder that helps the configuration of a bike.
pub struct BikeBuilder {
brakes: Option<Brake>,
wheels: Option<Wheel>,
transmission: Option<Transmission>,
}
impl BikeBuilder {
/// Adds brakes to the bike builder
pub fn with_brakes(mut self, brakes: Brake) -> Self {
self.brakes = Some(brakes);
self
}
/// Adds wheels to the bike builder
pub fn with_wheels(mut self, wheels: Wheel) -> Self {
self.wheels = Some(wheels);
self
}
/// Adds a transmission to the bike builder
pub fn with_transmission(mut self, transmission: Transmission) -> Self {
self.transmission = Some(transmission);
self
}
/// Builds the bike from the builder.
///
/// Will panic if the builder configuration is not correct
pub fn build(self) -> Bike {
Bike {
wheels: self.wheels.unwrap(),
transmission: self.transmission.unwrap(),
brakes: self.brakes.unwrap(),
}
}
}
fn main() {
let builder = Bike::builder();
let bike = builder.with_brakes(Brake::Disk)
.with_transmission(Transmission::GearHub)
.with_wheels(Wheel::Small)
.build();
println!("{bike:#?}");
bike.ride();
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment