chore: initialize containerized Rust learning workbook
This commit is contained in:
commit
05ffbd18bf
23 files changed
+549
No files matched your search
@@ -0,0 +1,4 @@
|
||||
[package]
|
||||
name = "ex05-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>` — 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
|
||||
```
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user