まとめ - Shape Enum
CoddyのRustジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 18/61。
チャレンジ
簡単異なる図形を表すために enum を使用し、それぞれが独自の寸法を保持する幾何計算機を作成しましょう。Shape enum は、single type で異なるデータ構造を保持し、method を通じて統一された動作を提供する方法を示します。
コードを整理するために、two ファイルを作成します。
shape.rs: publicShapeenum を Define し、two つの variant を持たせます。Circle: radius を表す single のf64を holds します(tuple syntax)Rectangle: named fields を holds します:width(f64)とheight(f64)
areamethod を Implement します。円には、πとして3.14159を使用します。main.rs: shape module を取り込み、provided inputs を使用して各 shape variant の one instance を作成し、それぞれの shape の area を Print します。
area method は f64 を return する必要があります。matching の際には、each variant を destructure して寸法を抽出し、appropriate な formula を適用します。
- Circle area:
π × radius² - Rectangle area:
width × height
出力では、each shape の area を独自の行に、ちょうど single 桁の小数点以下を付けて表示します。
Circle area: {area}
Rectangle area: {area}たとえば、circle の radius が 5.0 で、width が 4.0、height が 6.0 の rectangle の場合、出力は次のようになります。
Circle area: 78.5
Rectangle area: 24.0three つの入力を受け取ります:circle の radius、rectangle の width、rectangle の height です。
自分で試してみよう
mod shape;
use shape::Shape;
fn main() {
// 入力を読み取る
let mut radius_input = String::new();
std::io::stdin().read_line(&mut radius_input).expect("Failed to read line");
let radius: f64 = radius_input.trim().parse().expect("Invalid number");
let mut width_input = String::new();
std::io::stdin().read_line(&mut width_input).expect("Failed to read line");
let width: f64 = width_input.trim().parse().expect("Invalid number");
let mut height_input = String::new();
std::io::stdin().read_line(&mut height_input).expect("Failed to read line");
let height: f64 = height_input.trim().parse().expect("Invalid number");
// TODO: radiusを使用してCircle shapeを作成する
// TODO: widthとheightを使用してRectangle shapeを作成する
// TODO: 各shapeのareaを小数点以下1桁で出力する
// Format: "Circle area: {area}" and "Rectangle area: {area}"
}
オブジェクト指向プログラミングのすべてのレッスン
自分で練習してみよう: Rustオンラインコンパイラ