chore: initialize containerized Rust learning workbook

This commit is contained in:
soda64 committed 2026-11-30 22:07:47 +01:00
commit 05ffbd18bf
23 files changed
+549

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
[package]
name = "ex03-structs-enums"
version = "0.1.0"
edition = "2021"
+16
View File
@@ -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>`, `Result<T, E>`
## 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>` — zwróć `None` przy dzieleniu przez `0.0`, w przeciwnym razie `Some(a / b)`.
## Uruchomienie testów
```bash
make test PKG=ex03-structs-enums
```
+73
View File
@@ -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);
}
}