Menu
Coddy logo textTech

まとめ:表示可能な Point

CoddyのRustジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 39/61。

challenge icon

チャレンジ

簡単

学習した標準トレイトをすべて組み合わせて、デバッグや美しい表示ができ、等価性を比較できる、完全な機能を備えた Point 構造体を作成しましょう!

コードを2つのファイルに分けて整理します:

  • point.rs:public な Point 構造体を定義し、public な x および y フィールド(どちらも i32)を持たせます。Point は次の3つの機能をサポートする必要があります:
    • {:?} によるデバッグ出力。これを自動的に Derive します
    • {} を使った、形式 (x, y) でのユーザーフレンドリーな表示:std::fmt::Display を使って手動で Implement します
    • == による等価性比較:PartialEq を Derive します
  • main.rs:point モジュールを取り込み、提供された inputs を使って2つの Point instances を作成します。first の point を debug 形式で出力し、second の point を display 形式で出力し、2つの points が Equal かどうかを比較することで、3つの機能をすべて実演します。

output には、3つの trait の機能がすべて動作していることが示されます:

Debug: Point { x: {x1}, y: {y1} }
Display: ({x2}, {y2})
Equal: {true/false}

たとえば、inputs が 3535 の場合:

Debug: Point { x: 3, y: 5 }
Display: (3, 5)
Equal: true

また、inputs が 1020515 の場合:

Debug: Point { x: 10, y: 20 }
Display: (5, 15)
Equal: false

4つの inputs を受け取ります:first の point の x 座標と y 座標、続いて second の point の x 座標と y 座標です。それぞれを i32 として parse します。

自分で試してみよう

mod point;

use point::Point;

fn main() {
    // 4つの入力を読み取る: x1, y1, x2, y2
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let x1: i32 = input.trim().parse().expect("Invalid input");

    input.clear();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let y1: i32 = input.trim().parse().expect("Invalid input");

    input.clear();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let x2: i32 = input.trim().parse().expect("Invalid input");

    input.clear();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let y2: i32 = input.trim().parse().expect("Invalid input");

    // TODO: 入力を使って2つのPointインスタンスを作成する

    // TODO: デバッグ形式 {:?} を使って最初の点を出力する
    // 形式: "Debug: Point { x: ..., y: ... }"

    // TODO: 表示形式 {} を使って2番目の点を出力する
    // 形式: "Display: (..., ...)"

    // TODO: 2つの点を比較して結果を出力する
    // 形式: "Equal: true" または "Equal: false"
}

オブジェクト指向プログラミングのすべてのレッスン

自分で練習してみよう: Rustオンラインコンパイラ