0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rust でぽりもーふぃずむった

Posted at

trait でオブジェクト指向っぽいことをしよう

use std::io;

trait Animal {
  fn get_num(&self) -> u64;
}

struct Cat {
  num: u64,
}

struct Dog {
  num: u64,
}

impl Animal for Cat {
  fn get_num(&self) -> u64 {
    println!("Cat");
    self.num
  }
}

impl Animal for Dog {
  fn get_num(&self) -> u64 {
    println!("Dog");
    self.num
  }
}

fn main() {
    println!("1:Cat, 2:Dog");
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("failed");
    let input = input.trim();

    let cat = Cat{num: 1};
    let dog = Dog{num: 2};

    let animal: &dyn Animal = match input.as_ref() {
      "1" => &cat as &dyn Animal,
      "2" => &dog as &dyn Animal,
      _=> panic!("error"),
    };

    println!("num: {}", animal.get_num());
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?