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

+7
View File
@@ -0,0 +1,7 @@
/target
**/*.rs.bk
*.pdb
.DS_Store
.idea/
.vscode/
*.swp
Generated
+23
View File
@@ -0,0 +1,23 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "ex01-basics"
version = "0.1.0"
[[package]]
name = "ex02-ownership"
version = "0.1.0"
[[package]]
name = "ex03-structs-enums"
version = "0.1.0"
[[package]]
name = "ex04-collections-errors"
version = "0.1.0"
[[package]]
name = "ex05-generics-traits"
version = "0.1.0"
+5
View File
@@ -0,0 +1,5 @@
[workspace]
resolver = "2"
members = [
"exercises/*",
]
+5
View File
@@ -0,0 +1,5 @@
FROM docker.io/library/rust:1-slim
RUN rustup component add rustfmt clippy
WORKDIR /workspace
+55
View File
@@ -0,0 +1,55 @@
IMAGE ?= rust-learning:latest
ENGINE ?= podman
CARGO_CACHE ?= rust-learning-cargo-cache
PKG ?=
RUN_CONTAINER = $(ENGINE) run --rm \
-v "$(CURDIR):/workspace:Z" \
-v "$(CARGO_CACHE):/usr/local/cargo/registry" \
-w /workspace \
$(IMAGE)
.PHONY: help image check test clippy fmt fmt-check shell clean
help:
@echo "Dostępne komendy:"
@echo " make image - Zbuduj obraz kontenera Rust (jednorazowo)"
@echo " make check - Sprawdź kompilację całego workspace"
@echo " make test - Uruchom testy wszystkich ćwiczeń"
@echo " make test PKG=ex01-basics - Uruchom testy wybranego rozdziału"
@echo " make clippy - Uruchom linter Clippy"
@echo " make fmt - Sformatuj kod (rustfmt)"
@echo " make shell - Otwórz powłokę bash wewnątrz kontenera"
@echo " make clean - Usuń katalog target/"
image:
$(ENGINE) build -t $(IMAGE) -f Containerfile .
check:
$(RUN_CONTAINER) cargo check --workspace --tests
test:
ifdef PKG
$(RUN_CONTAINER) cargo test -p $(PKG) -- --nocapture
else
$(RUN_CONTAINER) cargo test --workspace
endif
clippy:
$(RUN_CONTAINER) cargo clippy --workspace --all-targets
fmt:
$(RUN_CONTAINER) cargo fmt --all
fmt-check:
$(RUN_CONTAINER) cargo fmt --all -- --check
shell:
$(ENGINE) run --rm -it \
-v "$(CURDIR):/workspace:Z" \
-v "$(CARGO_CACHE):/usr/local/cargo/registry" \
-w /workspace \
$(IMAGE) bash
clean:
$(RUN_CONTAINER) cargo clean
+49
View File
@@ -0,0 +1,49 @@
# Rust Learning Workbook
Zeszyt ćwiczeń do nauki języka Rust oparty na **Cargo Workspace** i izolowanym środowisku **Podman** (Zero Host Pollution).
## Architektura pracy (Model A — podział na gałęzie)
* **`main`** — czysty szablon: nierozwiązane zadania (`exercises/`) oraz wspólne notatki (`notes/`). **Nie commituj tutaj rozwiązań zadań.**
* **`attempt/<YYYY-MM>`** — gałąź robocza dla konkretnego podejścia do kursu (np. `attempt/2026-11`). Tutaj rozwiązujesz ćwiczenia i commitujesz postępy.
* **Powrót po czasie / start od nowa:**
```bash
git checkout main
git checkout -b attempt/2027-01
```
Twoje poprzednie podejścia zostają bezpiecznie w historii gałęzi na Gitei, a nowe zaczynasz z czystym zestawem zadań.
* **Notatki (`notes/`):** możesz je rozwijać na `main` (albo cherry-pickować / merge'ować między gałęziami), żeby zawsze były wspólne i aktualne.
## Szybki start (Podman)
Nie musisz instalować Rusta ani `cargo` na hoście — wszystko uruchamia się w kontenerze:
```bash
# 1. Zbuduj lokalny obraz z rustc, cargo, clippy i rustfmt (raz)
make image
# 2. Sprawdź, czy cały workspace się kompiluje
make check
# 3. Uruchom testy wybranego rozdziału
make test PKG=ex01-basics
# 4. Sformatuj kod i sprawdź podpowiedzi lintera
make fmt
make clippy
```
Gdy rozwiązujesz zadanie w pliku `exercises/<rozdział>/src/lib.rs`, usuń z góry pliku `#![allow(unused_variables, dead_code)]`, żeby kompilator i `clippy` pilnowały czystości kodu.
## Spis rozdziałów i postęp
- [ ] `ex01-basics` — [01-basics](exercises/01-basics/README.md): zmienne, typy, funkcje, przepływ sterowania
- [ ] `ex02-ownership` — [02-ownership](exercises/02-ownership/README.md): ownership, borrowing, slices
- [ ] `ex03-structs-enums` — [03-structs-enums](exercises/03-structs-enums/README.md): struktury, enumy, `match`, `Option`, `Result`
- [ ] `ex04-collections-errors` — [04-collections-errors](exercises/04-collections-errors/README.md): `Vec`, `HashMap`, `String`, propagacja błędów (`?`)
- [ ] `ex05-generics-traits` — [05-generics-traits](exercises/05-generics-traits/README.md): generyki, traity, lifetimes
## Notatki
* [Indeks notatek](notes/README.md)
* [Ściągawka Rust & Cargo](notes/00-cheatsheet.md)
+4
View File
@@ -0,0 +1,4 @@
[package]
name = "ex01-basics"
version = "0.1.0"
edition = "2021"
+18
View File
@@ -0,0 +1,18 @@
# 01 — Podstawy (Basics)
## Zakres
* Zmienne (`let`, `let mut`), shadowing
* Typy skalarne (`i32`, `u32`, `f64`, `bool`, `char`)
* Funkcje, wyrażenia vs instrukcje (*expressions vs statements*)
* Przepływ sterowania (`if`, `loop`, `while`, `for`)
## Zadania (`src/lib.rs`)
1. `celsius_to_fahrenheit(c: f64) -> f64` — przelicz temperaturę ze stopni Celsjusza na Fahrenheita ($F = C \cdot 1.8 + 32$).
2. `is_even(n: i32) -> bool` — zwróć `true`, jeśli liczba jest parzysta.
3. `sum_up_to(n: u32) -> u32` — oblicz sumę liczb od `1` do `n` włącznie (dla `0` zwróć `0`).
4. `fizzbuzz_label(n: u32) -> String` — klasyczny FizzBuzz dla pojedynczej liczby (`"Fizz"`, `"Buzz"`, `"FizzBuzz"` lub zapis liczby).
## Uruchomienie testów
```bash
make test PKG=ex01-basics
```
+53
View File
@@ -0,0 +1,53 @@
#![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 is_even(n: i32) -> bool {
todo!("Zwróć true jeśli n jest parzyste")
}
pub fn sum_up_to(n: u32) -> u32 {
todo!("Zsumuj liczby od 1 do n włącznie")
}
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 checks_even_numbers() {
assert!(is_even(0));
assert!(is_even(42));
assert!(is_even(-8));
assert!(!is_even(7));
assert!(!is_even(-3));
}
#[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 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");
}
}
+4
View File
@@ -0,0 +1,4 @@
[package]
name = "ex02-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, jeśli brak spacji.
2. `append_exclamation(s: &mut String)` — dopisz `'!'` na końcu przekazanego `String` bez przejmowania jego własności.
3. `sum_slice(values: &[i32]) -> i32` — policz sumę elementów wycinka `&[i32]`.
## Uruchomienie testów
```bash
make test PKG=ex02-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);
}
}
+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);
}
}
@@ -0,0 +1,4 @@
[package]
name = "ex04-collections-errors"
version = "0.1.0"
edition = "2021"
+16
View File
@@ -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, po podziale po białych znakach).
2. `parse_positive_i32(input: &str) -> Result<i32, ParsePositiveError>` — sparsuj tekst do `i32` i odrzuć wartości `<= 0` odpowiednim wariantem błędu.
3. `sum_parsed_positives(inputs: &[&str]) -> Result<i32, ParsePositiveError>` — zsumuj listę tekstów, propagując pierwszy napotkany błąd przez `?`.
## Uruchomienie testów
```bash
make test PKG=ex04-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)
);
}
}
+4
View File
@@ -0,0 +1,4 @@
[package]
name = "ex05-generics-traits"
version = "0.1.0"
edition = "2021"
+16
View File
@@ -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>` — zwróć referencję do największego elementu w wycinku (lub `None` dla pustego wycinka).
2. Zaimplementuj trait `Summary` dla struktury `Article`.
3. `longest<'a>(x: &'a str, y: &'a str) -> &'a str` — zwróć dłuższy z dwóch napisów (gdy równe, zwróć `x`).
## Uruchomienie testów
```bash
make test PKG=ex05-generics-traits
```
+51
View File
@@ -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");
}
}
+16
View File
@@ -0,0 +1,16 @@
# Ściągawka Rust & Cargo
## 3 zasady Ownership
1. Każda wartość w Ruście ma dokładnie jednego **właściciela** (*owner*).
2. W jednym momencie może istnieć tylko jeden właściciel.
3. Gdy właściciel wychodzi poza zakres (*scope*), wartość zostaje zwolniona (*drop*).
## Zasady Borrowing (pożyczania)
* W dowolnym momencie możesz mieć **albo** dowolną liczbę niemutowalnych referencji (`&T`), **albo** dokładnie jedną mutowalną referencję (`&mut T`).
* Referencje muszą być zawsze poprawne (*no dangling references*).
## Przydatne komendy (przez `make`)
* `make check` — szybkie sprawdzenie typów i borrow checkera bez budowania binarek
* `make test PKG=ex01-basics` — uruchomienie testów jednego rozdziału
* `make clippy` — idiomatyczne podpowiedzi lintera
* `make fmt` — automatyczne formatowanie kodu
+5
View File
@@ -0,0 +1,5 @@
# Notatki z nauki Rusta
Miejsce na własne notatki, podsumowania rozdziałów i najczęstsze błędy kompilatora.
* [00 — Ściągawka Rust & Cargo](00-cheatsheet.md)