feat: reorganize workbook into 3 tracks (core, engineering-2026, ecosystems)

This commit is contained in:
soda64 committed 2026-11-30 22:30:53 +01:00
1 parent 82677455b2
commit 2e002b6176
64 files changed
+2295 -196

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
[package]
name = "core01-basics"
version = "0.1.0"
edition = "2021"
+20
View File
@@ -0,0 +1,20 @@
# 01 — Podstawy, pętle, warunki i funkcje
## Zakres
* Zmienne (`let`, `let mut`), shadowing, typy skalarne, krotki i tablice
* Funkcje, wyrażenia vs instrukcje (*expressions vs statements*)
* Instrukcje warunkowe (`if` jako wyrażenie, `match` z zakresami i strażnikami `if`)
* Pętle (`loop` zwracające wartość, `while`, `for`)
## Zadania (`src/lib.rs`)
1. `celsius_to_fahrenheit(c: f64) -> f64` — przelicz temperaturę ($F = C \cdot 1.8 + 32$).
2. `classify_score(score: u8) -> &'static str` — użyj `match` z zakresami: `0..=49` -> `"fail"`, `50..=74` -> `"pass"`, `75..=89` -> `"good"`, `90..=100` -> `"excellent"`, powyżej `100` -> `"invalid"`.
3. `sum_up_to(n: u32) -> u32` — suma liczb od `1` do `n` włącznie (pętla `for`).
4. `first_power_of_two_gte(target: u32) -> u32` — znajdź najmniejszą potęgę dwójki $\ge \text{target}$ używając pętli `loop` lub `while` (np. dla `1` -> `1`, dla `5` -> `8`, dla `16` -> `16`).
5. `min_max(values: &[i32]) -> Option<(i32, i32)>` — zwróć krotkę `(min, max)` dla niepustego wycinka lub `None` dla pustego.
6. `fizzbuzz_label(n: u32) -> String` — `"Fizz"`, `"Buzz"`, `"FizzBuzz"` lub zapis liczby.
## Uruchomienie testów
```bash
make test PKG=core01-basics
```
+77
View File
@@ -0,0 +1,77 @@
#![allow(unused_variables, dead_code)]
pub fn celsius_to_fahrenheit(c: f64) -> f64 {
todo!("Przelicz stopnie Celsjusza na Fahrenheita: c * 1.8 + 32.0")
}
pub fn classify_score(score: u8) -> &'static str {
todo!("Użyj match z zakresami 0..=49, 50..=74, 75..=89, 90..=100, _")
}
pub fn sum_up_to(n: u32) -> u32 {
todo!("Zsumuj liczby od 1 do n włącznie")
}
pub fn first_power_of_two_gte(target: u32) -> u32 {
todo!("Znajdź najmniejszą potęgę dwójki >= target (dla 0 lub 1 zwróć 1)")
}
pub fn min_max(values: &[i32]) -> Option<(i32, i32)> {
todo!("Zwróć Some((min, max)) lub None dla pustego wycinka")
}
pub fn fizzbuzz_label(n: u32) -> String {
todo!("Zwróć Fizz / Buzz / FizzBuzz lub n.to_string()")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn converts_temperatures() {
assert!((celsius_to_fahrenheit(0.0) - 32.0).abs() < f64::EPSILON);
assert!((celsius_to_fahrenheit(100.0) - 212.0).abs() < f64::EPSILON);
assert!((celsius_to_fahrenheit(-40.0) - (-40.0)).abs() < f64::EPSILON);
}
#[test]
fn classifies_scores_with_ranges() {
assert_eq!(classify_score(0), "fail");
assert_eq!(classify_score(49), "fail");
assert_eq!(classify_score(50), "pass");
assert_eq!(classify_score(80), "good");
assert_eq!(classify_score(95), "excellent");
assert_eq!(classify_score(101), "invalid");
}
#[test]
fn sums_range() {
assert_eq!(sum_up_to(0), 0);
assert_eq!(sum_up_to(1), 1);
assert_eq!(sum_up_to(10), 55);
}
#[test]
fn finds_power_of_two() {
assert_eq!(first_power_of_two_gte(0), 1);
assert_eq!(first_power_of_two_gte(1), 1);
assert_eq!(first_power_of_two_gte(5), 8);
assert_eq!(first_power_of_two_gte(16), 16);
}
#[test]
fn computes_min_and_max() {
assert_eq!(min_max(&[]), None);
assert_eq!(min_max(&[42]), Some((42, 42)));
assert_eq!(min_max(&[3, -10, 7, 25, 0]), Some((-10, 25)));
}
#[test]
fn formats_fizzbuzz() {
assert_eq!(fizzbuzz_label(1), "1");
assert_eq!(fizzbuzz_label(3), "Fizz");
assert_eq!(fizzbuzz_label(5), "Buzz");
assert_eq!(fizzbuzz_label(15), "FizzBuzz");
}
}
@@ -0,0 +1,4 @@
[package]
name = "core02-ownership"
version = "0.1.0"
edition = "2021"
+16
View File
@@ -0,0 +1,16 @@
# 02 — Ownership, Borrowing i Slices
## Zakres
* Semantyka przenoszenia (*move*) vs kopiowania (*Copy*)
* Referencje niemutowalne (`&T`) i mutowalne (`&mut T`)
* Wycinki (*slices*): `&str`, `&[T]`
## Zadania (`src/lib.rs`)
1. `first_word(s: &str) -> &str` — zwróć pierwsze słowo (do pierwszej spacji) lub cały napis.
2. `append_exclamation(s: &mut String)` — dopisz `'!'` na końcu przekazanego `String` bez przejmowania własności.
3. `sum_slice(values: &[i32]) -> i32` — policz sumę elementów wycinka `&[i32]`.
## Uruchomienie testów
```bash
make test PKG=core02-ownership
```
+39
View File
@@ -0,0 +1,39 @@
#![allow(unused_variables, dead_code, clippy::ptr_arg)]
pub fn first_word(s: &str) -> &str {
todo!("Zwróć wycinek reprezentujący pierwsze słowo w s")
}
pub fn append_exclamation(s: &mut String) {
todo!("Dopisz '!' do s przez mutowalną referencję")
}
pub fn sum_slice(values: &[i32]) -> i32 {
todo!("Zwróć sumę elementów wycinka")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extracts_first_word() {
assert_eq!(first_word("hello world"), "hello");
assert_eq!(first_word("rust"), "rust");
assert_eq!(first_word(""), "");
}
#[test]
fn mutates_string_in_place() {
let mut msg = String::from("Rust");
append_exclamation(&mut msg);
assert_eq!(msg, "Rust!");
}
#[test]
fn sums_slice_elements() {
assert_eq!(sum_slice(&[]), 0);
assert_eq!(sum_slice(&[1, 2, 3, 4]), 10);
assert_eq!(sum_slice(&[-5, 5, 10]), 10);
}
}
@@ -0,0 +1,4 @@
[package]
name = "core03-structs-enums"
version = "0.1.0"
edition = "2021"
@@ -0,0 +1,16 @@
# 03 — Struktury, Enumy i Pattern Matching
## Zakres
* Definiowanie `struct` oraz metod w blokach `impl`
* `enum` z danymi (*algebraic data types*)
* `match`, `Option<T>`
## Zadania (`src/lib.rs`)
1. `Rectangle::area(&self) -> u32` oraz `Rectangle::can_hold(&self, other: &Rectangle) -> bool`.
2. `Shape::area(&self) -> f64` dla enuma `Shape` (`Circle(f64)` oraz `Rect { width: f64, height: f64 }`).
3. `safe_divide(a: f64, b: f64) -> Option<f64>` — `None` przy dzieleniu przez `0.0`, w przeciwnym razie `Some(a / b)`.
## Uruchomienie testów
```bash
make test PKG=core03-structs-enums
```
@@ -0,0 +1,73 @@
#![allow(unused_variables, dead_code)]
use std::f64::consts::PI;
#[derive(Debug, PartialEq)]
pub struct Rectangle {
pub width: u32,
pub height: u32,
}
impl Rectangle {
pub fn area(&self) -> u32 {
todo!("Oblicz pole prostokąta")
}
pub fn can_hold(&self, other: &Rectangle) -> bool {
todo!("Zwróć true jeśli self pomieści other (ściśle większe wymiary)")
}
}
#[derive(Debug, PartialEq)]
pub enum Shape {
Circle(f64),
Rect { width: f64, height: f64 },
}
impl Shape {
pub fn area(&self) -> f64 {
let _ = PI;
todo!("Użyj match na self i oblicz pole figury")
}
}
pub fn safe_divide(a: f64, b: f64) -> Option<f64> {
todo!("Zwróć None gdy b == 0.0, inaczej Some(a / b)")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn calculates_rectangle_methods() {
let big = Rectangle {
width: 30,
height: 50,
};
let small = Rectangle {
width: 10,
height: 40,
};
assert_eq!(big.area(), 1500);
assert!(big.can_hold(&small));
assert!(!small.can_hold(&big));
}
#[test]
fn calculates_shape_areas() {
let circle = Shape::Circle(2.0);
let rect = Shape::Rect {
width: 3.0,
height: 4.0,
};
assert!((circle.area() - (PI * 4.0)).abs() < 1e-9);
assert!((rect.area() - 12.0).abs() < 1e-9);
}
#[test]
fn divides_safely() {
assert_eq!(safe_divide(10.0, 2.0), Some(5.0));
assert_eq!(safe_divide(10.0, 0.0), None);
}
}
@@ -0,0 +1,4 @@
[package]
name = "core04-collections-errors"
version = "0.1.0"
edition = "2021"
@@ -0,0 +1,16 @@
# 04 — Kolekcje i Obsługa Błędów
## Zakres
* `Vec<T>`, `HashMap<K, V>`, `String`
* `Result<T, E>` i operator propagacji błędów `?`
* Własne typy błędów (`enum`)
## Zadania (`src/lib.rs`)
1. `word_counts(text: &str) -> HashMap<String, usize>` — policz wystąpienia słów (case-insensitive).
2. `parse_positive_i32(input: &str) -> Result<i32, ParsePositiveError>` — sparsuj tekst do `i32` i odrzuć wartości `<= 0`.
3. `sum_parsed_positives(inputs: &[&str]) -> Result<i32, ParsePositiveError>` — zsumuj listę tekstów, propagując pierwszy błąd przez `?`.
## Uruchomienie testów
```bash
make test PKG=core04-collections-errors
```
@@ -0,0 +1,66 @@
#![allow(unused_variables, dead_code)]
use std::collections::HashMap;
#[derive(Debug, PartialEq)]
pub enum ParsePositiveError {
InvalidNumber,
NotPositive,
}
pub fn word_counts(text: &str) -> HashMap<String, usize> {
todo!("Policz wystąpienia słów w text (lowercase)")
}
pub fn parse_positive_i32(input: &str) -> Result<i32, ParsePositiveError> {
todo!(
"Sparsuj input jako i32; jeśli błąd parsowania -> InvalidNumber, jeśli <= 0 -> NotPositive"
)
}
pub fn sum_parsed_positives(inputs: &[&str]) -> Result<i32, ParsePositiveError> {
todo!("Zsumuj wyniki parse_positive_i32 używając operatora ?")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn counts_words_case_insensitively() {
let counts = word_counts("Rust rust is fast and RUST is safe");
assert_eq!(counts.get("rust"), Some(&3));
assert_eq!(counts.get("is"), Some(&2));
assert_eq!(counts.get("fast"), Some(&1));
}
#[test]
fn parses_positive_numbers() {
assert_eq!(parse_positive_i32("42"), Ok(42));
assert_eq!(
parse_positive_i32("0"),
Err(ParsePositiveError::NotPositive)
);
assert_eq!(
parse_positive_i32("-5"),
Err(ParsePositiveError::NotPositive)
);
assert_eq!(
parse_positive_i32("abc"),
Err(ParsePositiveError::InvalidNumber)
);
}
#[test]
fn sums_and_propagates_errors() {
assert_eq!(sum_parsed_positives(&["1", "2", "3"]), Ok(6));
assert_eq!(
sum_parsed_positives(&["1", "0", "3"]),
Err(ParsePositiveError::NotPositive)
);
assert_eq!(
sum_parsed_positives(&["1", "oops"]),
Err(ParsePositiveError::InvalidNumber)
);
}
}
@@ -0,0 +1,4 @@
[package]
name = "core05-generics-traits"
version = "0.1.0"
edition = "2021"
@@ -0,0 +1,16 @@
# 05 — Generyki, Traity i Lifetimes
## Zakres
* Funkcje i typy generyczne (`<T: PartialOrd>`)
* Definiowanie i implementowanie traitów (`trait Summary`)
* Podstawowe adnotacje czasu życia (`'a`)
## Zadania (`src/lib.rs`)
1. `largest<T: PartialOrd>(items: &[T]) -> Option<&T>` — referencja do największego elementu lub `None`.
2. Zaimplementuj trait `Summary` dla `Article`.
3. `longest<'a>(x: &'a str, y: &'a str) -> &'a str` — dłuższy napis (przy równej długości zwróć `x`).
## Uruchomienie testów
```bash
make test PKG=core05-generics-traits
```
@@ -0,0 +1,51 @@
#![allow(unused_variables, dead_code)]
pub trait Summary {
fn summarize(&self) -> String;
}
pub struct Article {
pub title: String,
pub author: String,
}
impl Summary for Article {
fn summarize(&self) -> String {
todo!("Zwróć format: \"<title> by <author>\"")
}
}
pub fn largest<T: PartialOrd>(items: &[T]) -> Option<&T> {
todo!("Zwróć referencję do największego elementu w items lub None")
}
pub fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
todo!("Zwróć dłuższy wycinek (przy równej długości zwróć x)")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn summarizes_article() {
let article = Article {
title: String::from("Ownership in Rust"),
author: String::from("Ferris"),
};
assert_eq!(article.summarize(), "Ownership in Rust by Ferris");
}
#[test]
fn finds_largest_generic() {
assert_eq!(largest::<i32>(&[]), None);
assert_eq!(largest(&[3, 1, 9, 4]), Some(&9));
assert_eq!(largest(&['a', 'z', 'm']), Some(&'z'));
}
#[test]
fn picks_longest_slice() {
assert_eq!(longest("rust", "programming"), "programming");
assert_eq!(longest("same", "size"), "same");
}
}
@@ -0,0 +1,4 @@
[package]
name = "core06-iterators-closures"
version = "0.1.0"
edition = "2021"
@@ -0,0 +1,16 @@
# 06 — Iteratory i Domknięcia (Closures)
## Zakres
* Domknięcia i traity `Fn`, `FnMut`, `FnOnce`
* Łańcuchy iteratorów: `iter()`, `filter()`, `map()`, `fold()`, `collect()`
* Przetwarzanie bez zbędnych alokacji pośrednich
## Zadania (`src/lib.rs`)
1. `sum_of_even_squares(nums: &[i32]) -> i32` — wybierz liczby parzyste, podnieś do kwadratu i zsumuj używając iteratorów.
2. `filter_and_transform<F>(items: &[i32], predicate: F) -> Vec<i32>` — odfiltruj elementy spełniające `predicate` i pomnóż każdy przez 2.
3. `non_empty_trimmed(lines: &[&str]) -> Vec<String>` — przytnij białe znaki (`trim`) i odrzuć puste linie.
## Uruchomienie testów
```bash
make test PKG=core06-iterators-closures
```
@@ -0,0 +1,39 @@
#![allow(unused_variables, dead_code)]
pub fn sum_of_even_squares(nums: &[i32]) -> i32 {
todo!("Użyj iter().filter(...).map(...).sum()")
}
pub fn filter_and_transform<F>(items: &[i32], predicate: F) -> Vec<i32>
where
F: Fn(i32) -> bool,
{
todo!("Odfiltruj items przez predicate i pomnóż każdy przez 2")
}
pub fn non_empty_trimmed(lines: &[&str]) -> Vec<String> {
todo!("Przytnij białe znaki i zwróć tylko niepuste linie jako Vec<String>")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sums_even_squares() {
assert_eq!(sum_of_even_squares(&[1, 2, 3, 4, 5]), 20);
assert_eq!(sum_of_even_squares(&[1, 3, 5]), 0);
}
#[test]
fn applies_closure_predicate() {
let result = filter_and_transform(&[1, 5, 10, 15], |x| x >= 5);
assert_eq!(result, vec![10, 20, 30]);
}
#[test]
fn trims_and_drops_empty_lines() {
let input = [" rust ", "", " ", "\tcargo\n"];
assert_eq!(non_empty_trimmed(&input), vec!["rust", "cargo"]);
}
}
@@ -0,0 +1,4 @@
[package]
name = "core07-data-structures"
version = "0.1.0"
edition = "2021"
@@ -0,0 +1,16 @@
# 07 — Struktury Danych (Data Structures)
## Zakres
* Własny stos generyczny `Stack<T>` na bazie `Vec<T>`
* Kolejka `Queue<T>` na bazie `VecDeque<T>`
* Jednokierunkowa lista łączona `LinkedList<T>` z użyciem `Option<Box<Node<T>>>` (świetny trening dla `Option::take()` i ownershipu na stercie)
## Zadania (`src/lib.rs`)
1. Zaimplementuj `Stack<T>`: `new`, `push`, `pop`, `peek`, `is_empty`.
2. Zaimplementuj `Queue<T>`: `new`, `enqueue`, `dequeue`, `len`.
3. Zaimplementuj `LinkedList<T>`: `new`, `push_front`, `pop_front`.
## Uruchomienie testów
```bash
make test PKG=core07-data-structures
```
@@ -0,0 +1,122 @@
#![allow(unused_variables, dead_code)]
use std::collections::VecDeque;
#[derive(Debug, Default)]
pub struct Stack<T> {
items: Vec<T>,
}
impl<T> Stack<T> {
pub fn new() -> Self {
todo!("Utwórz pusty stos")
}
pub fn push(&mut self, value: T) {
todo!("Dodaj element na wierzch stosu")
}
pub fn pop(&mut self) -> Option<T> {
todo!("Zdejmij element z wierzchu stosu")
}
pub fn peek(&self) -> Option<&T> {
todo!("Zwróć referencję do wierzchu stosu bez zdejmowania")
}
pub fn is_empty(&self) -> bool {
todo!("Sprawdź, czy stos jest pusty")
}
}
#[derive(Debug, Default)]
pub struct Queue<T> {
items: VecDeque<T>,
}
impl<T> Queue<T> {
pub fn new() -> Self {
todo!("Utwórz pustą kolejkę")
}
pub fn enqueue(&mut self, value: T) {
todo!("Dodaj element na koniec kolejki (push_back)")
}
pub fn dequeue(&mut self) -> Option<T> {
todo!("Pobierz element z początku kolejki (pop_front)")
}
pub fn len(&self) -> usize {
todo!("Zwróć liczbę elementów w kolejce")
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
struct Node<T> {
value: T,
next: Option<Box<Node<T>>>,
}
#[derive(Default)]
pub struct LinkedList<T> {
head: Option<Box<Node<T>>>,
}
impl<T> LinkedList<T> {
pub fn new() -> Self {
todo!("Utwórz pustą listę")
}
pub fn push_front(&mut self, value: T) {
todo!("Wstaw nowy węzeł na początek listy używając self.head.take()")
}
pub fn pop_front(&mut self) -> Option<T> {
todo!("Zdejmij pierwszy węzeł używając self.head.take()")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stack_lifo_behavior() {
let mut stack = Stack::new();
assert!(stack.is_empty());
stack.push(10);
stack.push(20);
assert_eq!(stack.peek(), Some(&20));
assert_eq!(stack.pop(), Some(20));
assert_eq!(stack.pop(), Some(10));
assert_eq!(stack.pop(), None);
}
#[test]
fn queue_fifo_behavior() {
let mut queue = Queue::new();
queue.enqueue("first");
queue.enqueue("second");
assert_eq!(queue.len(), 2);
assert_eq!(queue.dequeue(), Some("first"));
assert_eq!(queue.dequeue(), Some("second"));
assert_eq!(queue.dequeue(), None);
}
#[test]
fn linked_list_push_and_pop_front() {
let mut list = LinkedList::new();
assert_eq!(list.pop_front(), None);
list.push_front(1);
list.push_front(2);
list.push_front(3);
assert_eq!(list.pop_front(), Some(3));
assert_eq!(list.pop_front(), Some(2));
assert_eq!(list.pop_front(), Some(1));
assert_eq!(list.pop_front(), None);
}
}
@@ -0,0 +1,4 @@
[package]
name = "core08-oop-composition"
version = "0.1.0"
edition = "2021"
@@ -0,0 +1,16 @@
# 08 — Obiektowość po Rustowemu (Kompozycja zamiast Dziedziczenia)
Rust celowo **nie posiada dziedziczenia klas** (`extends`). Zamiast tego łączy:
* **enkapsulację** (prywatne pola + publiczne metody),
* **kompozycję** (struktura posiada inne struktury),
* **polimorfizm oparty o traity** (zarówno statyczny, jak i dynamiczny `Box<dyn Trait>`).
## Zadania (`src/lib.rs`)
1. `BankAccount` — enkapsulacja salda (`balance` prywatne): `new`, `deposit`, `withdraw` (zwraca `bool`), `balance`.
2. `Notifier` trait z domyślną metodą `prefix(&self) -> &str` oraz implementacje `EmailNotifier` i `SmsNotifier`.
3. `AlertService` — kompozycja z heterogeniczną listą `Vec<Box<dyn Notifier>>`: metoda `broadcast(&self, msg: &str) -> Vec<String>`.
## Uruchomienie testów
```bash
make test PKG=core08-oop-composition
```
@@ -0,0 +1,100 @@
#![allow(unused_variables, dead_code)]
pub struct BankAccount {
balance: u64,
}
impl BankAccount {
pub fn new(initial_balance: u64) -> Self {
todo!("Zainicjalizuj konto z initial_balance")
}
pub fn deposit(&mut self, amount: u64) {
todo!("Dodaj amount do salda")
}
pub fn withdraw(&mut self, amount: u64) -> bool {
todo!("Wypłać amount jeśli balance >= amount i zwróć true; inaczej false")
}
pub fn balance(&self) -> u64 {
todo!("Zwróć aktualne saldo")
}
}
pub trait Notifier {
fn channel(&self) -> &str;
fn format_message(&self, msg: &str) -> String {
format!("[{}] {}", self.channel(), msg)
}
}
pub struct EmailNotifier {
pub address: String,
}
impl Notifier for EmailNotifier {
fn channel(&self) -> &str {
todo!("Zwróć \"email\"")
}
}
pub struct SmsNotifier {
pub phone: String,
}
impl Notifier for SmsNotifier {
fn channel(&self) -> &str {
todo!("Zwróć \"sms\"")
}
}
#[derive(Default)]
pub struct AlertService {
notifiers: Vec<Box<dyn Notifier>>,
}
impl AlertService {
pub fn new() -> Self {
todo!("Utwórz pusty AlertService")
}
pub fn register(&mut self, notifier: Box<dyn Notifier>) {
todo!("Dodaj notifier do listy")
}
pub fn broadcast(&self, msg: &str) -> Vec<String> {
todo!("Wywołaj format_message(msg) na każdym notifierze i zbierz wyniki")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encapsulates_bank_account_balance() {
let mut acc = BankAccount::new(100);
acc.deposit(50);
assert_eq!(acc.balance(), 150);
assert!(acc.withdraw(40));
assert_eq!(acc.balance(), 110);
assert!(!acc.withdraw(500));
assert_eq!(acc.balance(), 110);
}
#[test]
fn broadcasts_via_dynamic_dispatch() {
let mut service = AlertService::new();
service.register(Box::new(EmailNotifier {
address: String::from("dev@example.com"),
}));
service.register(Box::new(SmsNotifier {
phone: String::from("+48123456789"),
}));
let sent = service.broadcast("Disk 90% full");
assert_eq!(sent, vec!["[email] Disk 90% full", "[sms] Disk 90% full"]);
}
}
@@ -0,0 +1,4 @@
[package]
name = "core09-design-patterns"
version = "0.1.0"
edition = "2021"
@@ -0,0 +1,18 @@
# 09 — Idiomatyczne Wzorce Projektowe w Ruście
Zamiast kopiować 1:1 wzorce z Javy/C++, Rust promuje wzorce wykorzystujące system typów i ownership:
* **Newtype** — osobny typ dla identyfikatorów (zapobiega pomyleniu `UserId` z `OrderId`).
* **Builder** — bezpieczna konstrukcja obiektów z wieloma opcjami.
* **Typestate** — stany obiektu wymuszane na etapie kompilacji (`Draft` -> `Published`).
* **Strategy** — wstrzykiwanie zachowania przez trait.
## Zadania (`src/lib.rs`)
1. `UserId(u64)` i `OrderId(u64)` — wzorzec Newtype.
2. `HttpRequestBuilder` — wzorzec Builder z metodami łańcuchowymi (`method`, `header`, `build`).
3. `Document<Draft>` -> `publish()` -> `Document<Published>` — wzorzec Typestate (`PhantomData`).
4. `DiscountStrategy` + `PercentageDiscount` + `apply_discount` — wzorzec Strategy.
## Uruchomienie testów
```bash
make test PKG=core09-design-patterns
```
@@ -0,0 +1,132 @@
#![allow(unused_variables, dead_code, unused_mut)]
use std::marker::PhantomData;
// --- 1. Newtype ---
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UserId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OrderId(pub u64);
pub fn format_audit_entry(user: UserId, order: OrderId) -> String {
todo!("Zwróć \"user:<id> order:<id>\"")
}
// --- 2. Builder ---
#[derive(Debug, PartialEq)]
pub struct HttpRequest {
pub url: String,
pub method: String,
pub timeout_ms: u64,
}
pub struct HttpRequestBuilder {
url: String,
method: String,
timeout_ms: u64,
}
impl HttpRequestBuilder {
pub fn new(url: impl Into<String>) -> Self {
todo!("Utwórz builder z domyślną metodą \"GET\" i timeout_ms = 3000")
}
pub fn method(mut self, method: impl Into<String>) -> Self {
todo!("Ustaw method i zwróć self")
}
pub fn timeout_ms(mut self, timeout_ms: u64) -> Self {
todo!("Ustaw timeout_ms i zwróć self")
}
pub fn build(self) -> HttpRequest {
todo!("Zbuduj HttpRequest")
}
}
// --- 3. Typestate ---
pub struct Draft;
pub struct Published;
pub struct Document<State> {
title: String,
_state: PhantomData<State>,
}
impl Document<Draft> {
pub fn new(title: impl Into<String>) -> Self {
todo!("Utwórz dokument w stanie Draft")
}
pub fn publish(self) -> Document<Published> {
todo!("Przejdź ze stanu Draft do Published")
}
}
impl Document<Published> {
pub fn title(&self) -> &str {
&self.title
}
}
// --- 4. Strategy ---
pub trait DiscountStrategy {
fn discount(&self, price_cents: u64) -> u64;
}
pub struct PercentageDiscount {
pub percent: u64,
}
impl DiscountStrategy for PercentageDiscount {
fn discount(&self, price_cents: u64) -> u64 {
todo!("Oblicz rabat: price_cents * self.percent / 100")
}
}
pub fn final_price(price_cents: u64, strategy: &dyn DiscountStrategy) -> u64 {
todo!("Zwróć cenę po rabacie (saturating_sub)")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn newtype_formats_audit_entry() {
assert_eq!(
format_audit_entry(UserId(7), OrderId(42)),
"user:7 order:42"
);
}
#[test]
fn builder_constructs_request() {
let req = HttpRequestBuilder::new("https://example.com")
.method("POST")
.timeout_ms(5000)
.build();
assert_eq!(
req,
HttpRequest {
url: String::from("https://example.com"),
method: String::from("POST"),
timeout_ms: 5000,
}
);
}
#[test]
fn typestate_transitions_draft_to_published() {
let draft = Document::new("Rust Patterns");
let published = draft.publish();
assert_eq!(published.title(), "Rust Patterns");
}
#[test]
fn strategy_calculates_discounted_price() {
let strategy = PercentageDiscount { percent: 20 };
assert_eq!(final_price(1000, &strategy), 800);
}
}
@@ -0,0 +1,4 @@
[package]
name = "core10-crud-repository"
version = "0.1.0"
edition = "2021"
@@ -0,0 +1,20 @@
# 10 — CRUD w pamięci (In-Memory Repository)
## Zakres
* Operacje **Create, Read, Update, Delete** na strukturze domenowej `Task`
* Walidacja wejścia (pusty tytuł -> `RepoError::InvalidTitle`)
* Zarządzanie stanem i auto-inkrementacją ID w `BTreeMap<u64, Task>` (deterministyczna kolejność)
## Zadania (`src/lib.rs`)
Zaimplementuj `TaskStore`:
1. `create(&mut self, title: impl Into<String>) -> Result<Task, RepoError>`
2. `get(&self, id: u64) -> Option<&Task>`
3. `list(&self) -> Vec<&Task>`
4. `update_title(&mut self, id: u64, title: impl Into<String>) -> Result<Task, RepoError>`
5. `mark_done(&mut self, id: u64) -> Result<Task, RepoError>`
6. `delete(&mut self, id: u64) -> Result<Task, RepoError>`
## Uruchomienie testów
```bash
make test PKG=core10-crud-repository
```
@@ -0,0 +1,85 @@
#![allow(unused_variables, dead_code)]
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Task {
pub id: u64,
pub title: String,
pub done: bool,
}
#[derive(Debug, PartialEq, Eq)]
pub enum RepoError {
InvalidTitle,
NotFound(u64),
}
#[derive(Default)]
pub struct TaskStore {
next_id: u64,
tasks: BTreeMap<u64, Task>,
}
impl TaskStore {
pub fn new() -> Self {
Self {
next_id: 1,
tasks: BTreeMap::new(),
}
}
pub fn create(&mut self, title: impl Into<String>) -> Result<Task, RepoError> {
todo!("Odrzuć pusty/samych-spacji tytuł (InvalidTitle), zapisz i zwróć Task")
}
pub fn get(&self, id: u64) -> Option<&Task> {
todo!("Zwróć referencję do zadania po id")
}
pub fn list(&self) -> Vec<&Task> {
todo!("Zwróć wszystkie zadania posortowane po id")
}
pub fn update_title(&mut self, id: u64, title: impl Into<String>) -> Result<Task, RepoError> {
todo!("Zwaliduj tytuł, zaktualizuj istniejące zadanie lub zwróć NotFound(id)")
}
pub fn mark_done(&mut self, id: u64) -> Result<Task, RepoError> {
todo!("Ustaw done = true lub zwróć NotFound(id)")
}
pub fn delete(&mut self, id: u64) -> Result<Task, RepoError> {
todo!("Usuń i zwróć zadanie lub NotFound(id)")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn full_crud_lifecycle() {
let mut store = TaskStore::new();
assert_eq!(store.create(" "), Err(RepoError::InvalidTitle));
let t1 = store.create("Learn Rust").unwrap();
let t2 = store.create("Build CLI").unwrap();
assert_eq!(t1.id, 1);
assert_eq!(t2.id, 2);
assert_eq!(store.list().len(), 2);
let updated = store.update_title(1, "Master Rust").unwrap();
assert_eq!(updated.title, "Master Rust");
let done = store.mark_done(1).unwrap();
assert!(done.done);
assert!(store.get(1).unwrap().done);
let removed = store.delete(2).unwrap();
assert_eq!(removed.id, 2);
assert_eq!(store.delete(2), Err(RepoError::NotFound(2)));
assert_eq!(store.list().len(), 1);
}
}