Skip to content

Instantly share code, notes, and snippets.

@kellypleahy
Created September 23, 2016 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kellypleahy/908ec1e4be2e1c7fffb547ffc3a1dbc1 to your computer and use it in GitHub Desktop.
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.
#![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