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());
}