復習 - 座標点
CoddyのRustジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 28/61。
チャレンジ
簡単あらゆる数値型で動作する柔軟な座標系を構築しましょう!整数を使ってグリッドベースのゲームの位置を表したり、floating-point numberを使って精密なグラフィックスの位置を表したりできる、汎用的な Point structを1つの定義から作成します。
コードを2つのファイルに整理します。
point.rs: 2つの public fields、xとy(どちらも型はT)を持つ、public genericPoint<T>structをDefineします。pointのmethodsをImplementします。- x座標とy座標からpointを作成する
newassociated function - dxとdyの値を受け取り、それらの量だけ座標を移動した新しい
Pointをreturnsするtranslatemethod(これにはTがadditionとcopyingをsupportすることがrequiresされるため、boundT: std::ops::Add<Output = T> + Copyをusingします)
- x座標とy座標からpointを作成する
main.rs: point moduleを取り込み、同じgeneric structが異なる数値型でシームレスに動作する方法を示します。
main fileでは、generic Point を次のように使用して示します。
- 最初の2つのinputs(
i32としてparsed)をusingしてinteger pointをCreateする - 3番目と4番目のinputs(こちらも
i32)でそれをTranslateする - 5番目と6番目のinputs(
f64としてparsed)をusingしてfloating-point pointをCreateする - 3つすべてのpointを表示する
Outputは次のformatに従う必要があります。
Integer point: ({x}, {y})
After translation: ({x}, {y})
Float point: ({x}, {y})たとえば、inputsが 3、5、2、-1、1.5、2.5 の場合:
Integer point: (3, 5)
After translation: (5, 4)
Float point: (1.5, 2.5)Point::new(3, 5) が Point<i32> をCreateする一方で、Point::new(1.5, 2.5) は Point<f64> をCreateすることに注目してください。同じstruct definitionが両方に適応します!
6つのinputsを受け取ります。最初のpoint用の2つのintegers、translation用の2つのintegers、そして2番目のpoint用の2つのfloatsです。
自分で試してみよう
mod point;
use point::Point;
fn main() {
// 入力を読み取る
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 dx: i32 = input.trim().parse().expect("Invalid input");
input.clear();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
let dy: i32 = input.trim().parse().expect("Invalid input");
input.clear();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
let x2: f64 = input.trim().parse().expect("Invalid input");
input.clear();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
let y2: f64 = input.trim().parse().expect("Invalid input");
// TODO: Create an integer point using x1 and y1
// TODO: Translate the integer point by dx and dy
// TODO: x2 と y2 を使用して浮動小数点の点を作成する
// TODO: 必要な形式で結果を出力する:
// println!("Integer point: ({}, {})", ...);
// println!("After translation: ({}, {})", ...);
// println!("Float point: ({}, {})", ...);
}
オブジェクト指向プログラミングのすべてのレッスン
自分で練習してみよう: Rustオンラインコンパイラ