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 = "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");
}
}