Files
rust-otus/practice/src/bin/e_summary.rs
2026-01-16 17:01:52 +03:00

60 lines
2.0 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 1. Создайте типаж Summary с методом summarize(&self) -> String.
// 2. Реализуйте его длā:
// ○ Vec<T> (где T: ToString), метод должен соединять элементы через запятую.
// ○ HashMap<K, V> (где K: ToString, V: ToString), метод должен выводить пары key:value.
// 3. Напиúите функøиĀ print_summary<T: Summary>(item: T), которая печатает результат summarize().
use std::collections::HashMap;
// Определяем типаж Summary
trait Summary {
fn summarize(&self) -> String;
}
// Реализация для Vec<T> где T: ToString
impl<T: ToString> Summary for Vec<T> {
fn summarize(&self) -> String {
self.iter()
.map(|v| v.to_string())
.collect::<Vec<String>>()
.join(",")
.to_string()
}
}
// Реализация для HashMap<K, V> где K: ToString, V: ToString
impl<K: ToString, V: ToString> Summary for HashMap<K, V> {
fn summarize(&self) -> String {
self.iter()
.map(|(k, v)| format!("{}:{}", k.to_string(), v.to_string()))
.collect::<Vec<String>>()
.join(", ")
}
}
// Обобщённая функция для вывода сводки
fn print_summary(summary: impl Summary) {
println!("{}", summary.summarize())
}
fn main() {
// Пример с вектором
let vec = vec![1, 2, 3];
print_summary(vec); // "1, 2, 3"
// Пример с HashMap
let mut map = HashMap::new();
map.insert("name", "Alice");
map.insert("age", "30");
print_summary(map); // "name:Alice, age:30" (порядок может отличаться)
// Дополнительный пример с разными типами
let words = vec!["hello", "world"];
print_summary(words); // "hello, world"
let mut scores = HashMap::new();
scores.insert("math", 95);
scores.insert("science", 90);
print_summary(scores); // "math:95, science:90"
}