Created
September 23, 2016 22:56
-
-
Save kellypleahy/908ec1e4be2e1c7fffb547ffc3a1dbc1 to your computer and use it in GitHub Desktop.
RUST: Using traits to implement generic Point<T> and Line<T> with a len() function that computes as f64.
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
#![allow(dead_code)] | |
#![allow(unused_imports)] | |
use std::mem; | |
use std::ops; | |
use std::convert; | |
struct Point<T> { | |
x: T, | |
y: T | |
} | |
impl<T> Point<T> { | |
fn new(x: T, y: T) -> Point<T> { Point { x: x, y: y } } | |
} | |
struct Line<T> { | |
start: Point<T>, | |
end: Point<T> | |
} | |
impl<T> Line<T> { | |
fn new(x1: T, x2: T, y1: T, y2: T) -> Line<T> { Line { start: Point::new(x1, y1), end: Point::new(x2, y2) } } | |
} | |
impl<T:ops::Sub+convert::Into<f64>> Line<T> where f64: std::convert::From<<T as std::ops::Sub>::Output> { | |
fn len(self) -> f64 { | |
let dx:f64 = (self.start.x - self.end.x).into(); | |
let dy:f64 = (self.start.y - self.end.y).into(); | |
(dx * dx + dy * dy).sqrt() | |
} | |
} | |
fn methods() { | |
let ln = Line::new(1, 2, 5, 2); | |
println!("{}", ln.len()); | |
} | |
fn main() { | |
methods(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment