From 05ffbd18bfb86cb060da8e2d98e4b08be4f67752 Mon Sep 17 00:00:00 2001 From: Mateusz Stomski Date: Mon, 30 Nov 2026 22:07:47 +0100 Subject: [PATCH] chore: initialize containerized Rust learning workbook --- .gitignore | 7 +++ Cargo.lock | 23 +++++++ Cargo.toml | 5 ++ Containerfile | 5 ++ Makefile | 55 ++++++++++++++++ README.md | 49 +++++++++++++++ exercises/01-basics/Cargo.toml | 4 ++ exercises/01-basics/README.md | 18 ++++++ exercises/01-basics/src/lib.rs | 53 ++++++++++++++++ exercises/02-ownership/Cargo.toml | 4 ++ exercises/02-ownership/README.md | 16 +++++ exercises/02-ownership/src/lib.rs | 39 ++++++++++++ exercises/03-structs-enums/Cargo.toml | 4 ++ exercises/03-structs-enums/README.md | 16 +++++ exercises/03-structs-enums/src/lib.rs | 73 ++++++++++++++++++++++ exercises/04-collections-errors/Cargo.toml | 4 ++ exercises/04-collections-errors/README.md | 16 +++++ exercises/04-collections-errors/src/lib.rs | 66 +++++++++++++++++++ exercises/05-generics-traits/Cargo.toml | 4 ++ exercises/05-generics-traits/README.md | 16 +++++ exercises/05-generics-traits/src/lib.rs | 51 +++++++++++++++ notes/00-cheatsheet.md | 16 +++++ notes/README.md | 5 ++ 23 files changed, 549 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 Containerfile create mode 100644 Makefile create mode 100644 README.md create mode 100644 exercises/01-basics/Cargo.toml create mode 100644 exercises/01-basics/README.md create mode 100644 exercises/01-basics/src/lib.rs create mode 100644 exercises/02-ownership/Cargo.toml create mode 100644 exercises/02-ownership/README.md create mode 100644 exercises/02-ownership/src/lib.rs create mode 100644 exercises/03-structs-enums/Cargo.toml create mode 100644 exercises/03-structs-enums/README.md create mode 100644 exercises/03-structs-enums/src/lib.rs create mode 100644 exercises/04-collections-errors/Cargo.toml create mode 100644 exercises/04-collections-errors/README.md create mode 100644 exercises/04-collections-errors/src/lib.rs create mode 100644 exercises/05-generics-traits/Cargo.toml create mode 100644 exercises/05-generics-traits/README.md create mode 100644 exercises/05-generics-traits/src/lib.rs create mode 100644 notes/00-cheatsheet.md create mode 100644 notes/README.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..16554e7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/target +**/*.rs.bk +*.pdb +.DS_Store +.idea/ +.vscode/ +*.swp diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..d5860b5 --- /dev/null +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4c6d3d5 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,5 @@ +[workspace] +resolver = "2" +members = [ + "exercises/*", +] diff --git a/Containerfile b/Containerfile new file mode 100644 index 0000000..dd50e86 --- /dev/null +++ b/Containerfile @@ -0,0 +1,5 @@ +FROM docker.io/library/rust:1-slim + +RUN rustup component add rustfmt clippy + +WORKDIR /workspace diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..984725c --- /dev/null +++ b/Makefile @@ -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 diff --git a/README.md b/README.md new file mode 100644 index 0000000..2e40ad3 --- /dev/null +++ b/README.md @@ -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/`** — 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//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) diff --git a/exercises/01-basics/Cargo.toml b/exercises/01-basics/Cargo.toml new file mode 100644 index 0000000..8f2d2fe --- /dev/null +++ b/exercises/01-basics/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "ex01-basics" +version = "0.1.0" +edition = "2021" diff --git a/exercises/01-basics/README.md b/exercises/01-basics/README.md new file mode 100644 index 0000000..c07ec0b --- /dev/null +++ b/exercises/01-basics/README.md @@ -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 +``` diff --git a/exercises/01-basics/src/lib.rs b/exercises/01-basics/src/lib.rs new file mode 100644 index 0000000..615b959 --- /dev/null +++ b/exercises/01-basics/src/lib.rs @@ -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"); + } +} diff --git a/exercises/02-ownership/Cargo.toml b/exercises/02-ownership/Cargo.toml new file mode 100644 index 0000000..fa48cfc --- /dev/null +++ b/exercises/02-ownership/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "ex02-ownership" +version = "0.1.0" +edition = "2021" diff --git a/exercises/02-ownership/README.md b/exercises/02-ownership/README.md new file mode 100644 index 0000000..7eeb7d7 --- /dev/null +++ b/exercises/02-ownership/README.md @@ -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 +``` diff --git a/exercises/02-ownership/src/lib.rs b/exercises/02-ownership/src/lib.rs new file mode 100644 index 0000000..790e844 --- /dev/null +++ b/exercises/02-ownership/src/lib.rs @@ -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); + } +} diff --git a/exercises/03-structs-enums/Cargo.toml b/exercises/03-structs-enums/Cargo.toml new file mode 100644 index 0000000..d508871 --- /dev/null +++ b/exercises/03-structs-enums/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "ex03-structs-enums" +version = "0.1.0" +edition = "2021" diff --git a/exercises/03-structs-enums/README.md b/exercises/03-structs-enums/README.md new file mode 100644 index 0000000..e7aca20 --- /dev/null +++ b/exercises/03-structs-enums/README.md @@ -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`, `Result` + +## 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` — zwróć `None` przy dzieleniu przez `0.0`, w przeciwnym razie `Some(a / b)`. + +## Uruchomienie testów +```bash +make test PKG=ex03-structs-enums +``` diff --git a/exercises/03-structs-enums/src/lib.rs b/exercises/03-structs-enums/src/lib.rs new file mode 100644 index 0000000..35608ea --- /dev/null +++ b/exercises/03-structs-enums/src/lib.rs @@ -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 { + 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); + } +} diff --git a/exercises/04-collections-errors/Cargo.toml b/exercises/04-collections-errors/Cargo.toml new file mode 100644 index 0000000..ce3e8ab --- /dev/null +++ b/exercises/04-collections-errors/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "ex04-collections-errors" +version = "0.1.0" +edition = "2021" diff --git a/exercises/04-collections-errors/README.md b/exercises/04-collections-errors/README.md new file mode 100644 index 0000000..939fb11 --- /dev/null +++ b/exercises/04-collections-errors/README.md @@ -0,0 +1,16 @@ +# 04 — Kolekcje i Obsługa Błędów + +## Zakres +* `Vec`, `HashMap`, `String` +* `Result` i operator propagacji błędów `?` +* Własne typy błędów (`enum`) + +## Zadania (`src/lib.rs`) +1. `word_counts(text: &str) -> HashMap` — policz wystąpienia słów (case-insensitive, po podziale po białych znakach). +2. `parse_positive_i32(input: &str) -> Result` — sparsuj tekst do `i32` i odrzuć wartości `<= 0` odpowiednim wariantem błędu. +3. `sum_parsed_positives(inputs: &[&str]) -> Result` — zsumuj listę tekstów, propagując pierwszy napotkany błąd przez `?`. + +## Uruchomienie testów +```bash +make test PKG=ex04-collections-errors +``` diff --git a/exercises/04-collections-errors/src/lib.rs b/exercises/04-collections-errors/src/lib.rs new file mode 100644 index 0000000..26db3d6 --- /dev/null +++ b/exercises/04-collections-errors/src/lib.rs @@ -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 { + todo!("Policz wystąpienia słów w text (lowercase)") +} + +pub fn parse_positive_i32(input: &str) -> Result { + todo!( + "Sparsuj input jako i32; jeśli błąd parsowania -> InvalidNumber, jeśli <= 0 -> NotPositive" + ) +} + +pub fn sum_parsed_positives(inputs: &[&str]) -> Result { + 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) + ); + } +} diff --git a/exercises/05-generics-traits/Cargo.toml b/exercises/05-generics-traits/Cargo.toml new file mode 100644 index 0000000..6cd838d --- /dev/null +++ b/exercises/05-generics-traits/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "ex05-generics-traits" +version = "0.1.0" +edition = "2021" diff --git a/exercises/05-generics-traits/README.md b/exercises/05-generics-traits/README.md new file mode 100644 index 0000000..5a41a37 --- /dev/null +++ b/exercises/05-generics-traits/README.md @@ -0,0 +1,16 @@ +# 05 — Generyki, Traity i Lifetimes + +## Zakres +* Funkcje i typy generyczne (``) +* Definiowanie i implementowanie traitów (`trait Summary`) +* Podstawowe adnotacje czasu życia (`'a`) + +## Zadania (`src/lib.rs`) +1. `largest(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 +``` diff --git a/exercises/05-generics-traits/src/lib.rs b/exercises/05-generics-traits/src/lib.rs new file mode 100644 index 0000000..ebd22f1 --- /dev/null +++ b/exercises/05-generics-traits/src/lib.rs @@ -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: \" 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"); + } +} diff --git a/notes/00-cheatsheet.md b/notes/00-cheatsheet.md new file mode 100644 index 0000000..cac8b73 --- /dev/null +++ b/notes/00-cheatsheet.md @@ -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 diff --git a/notes/README.md b/notes/README.md new file mode 100644 index 0000000..e96538a --- /dev/null +++ b/notes/README.md @@ -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)