Last active
June 4, 2023 18:03
-
-
Save segfo/7be4a1f702d876934eac2e23939dc886 to your computer and use it in GitHub Desktop.
ポリモーフィズムをRustでやってみる
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 参考:https://qiita.com/Nossa/items/a93024e653ff939115c6 | |
trait Shape{ | |
fn area(&self)->f32; | |
fn whoami(&self)->String; | |
} | |
struct Triangle { | |
pub base:f32, | |
pub height:f32 | |
} | |
impl Triangle{ | |
pub fn new(base:f32,height:f32)->Self{ | |
Triangle{base:base,height:height} | |
} | |
} | |
impl Shape for Triangle{ | |
fn area(&self)->f32{self.base * self.height / 2.0} | |
fn whoami(&self)->String{ | |
format!("I'm Triangle!\nbase: {} height: {}",self.base,self.height) | |
} | |
} | |
struct Circle { | |
pub radius:f32 | |
} | |
impl Circle{ | |
pub fn new(radius:f32)->Self{ | |
Circle{radius:radius} | |
} | |
} | |
impl Shape for Circle{ | |
fn area(&self)->f32{self.radius*self.radius*3.1415926535} | |
fn whoami(&self)->String{ | |
format!("I'm Circle!\nradius: {}",self.radius) | |
} | |
} | |
struct Rectangle { | |
pub width:f32, | |
pub height:f32 | |
} | |
impl Rectangle{ | |
pub fn new(width:f32,height:f32)->Self{ | |
Rectangle{width:width,height:height} | |
} | |
} | |
impl Shape for Rectangle{ | |
fn area(&self)->f32{self.width*self.height} | |
fn whoami(&self)->String{ | |
format!("I'm Rectangle!\nwidth: {} height: {}",self.width,self.height) | |
} | |
} | |
fn main(){ | |
for o in &[Box::new(Rectangle::new(10.0,20.0)) as Box<Shape>, | |
Box::new(Triangle::new(10.0,20.0)) as Box<Shape>, | |
Box::new(Circle::new(30.0)) as Box<Shape>]{ | |
println!("{}",o.whoami()); | |
println!("area : {}\n",o.area()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment