Files
rust-otus/practice/src/bin/b_pair.rs
2026-01-12 21:13:17 +03:00

36 lines
1.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.
// Создайте структуру Pair<T, U> с двумā полāми разнýх типов:
// ● Реализуйте метод new(first: T, second: U) -> Self.
// ● Добавþте метод swap(self) -> Pair<U, T>, которýй менāет местами знаùениā полей.
#![allow(clippy::approx_constant)]
#[derive(Debug)]
struct Pair<T, U> {
first: T,
second: U,
}
impl<T, U> Pair<T, U> {
// Создаем новую пару
fn new(first: T, second: U) -> Self {
Self { first, second }
}
// Меняем местами значения
fn swap(self) -> Pair<U, T> {
Pair::new(self.second, self.first)
}
}
fn main() {
let pair = Pair::new(42, "hello");
let swapped = pair.swap();
println!("{:?}", swapped); // Pair("hello", 42)
// Дополнительный пример с другими типами
let float_str_pair = Pair::new(3.14, "pi");
let swapped_pair = float_str_pair.swap();
println!("{:?}", swapped_pair); // Pair("pi", 3.14)
}