Skip to content

Instantly share code, notes, and snippets.

@spastorino
Last active August 29, 2015 14:13
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 spastorino/6873dc7f371fb0fa7651 to your computer and use it in GitHub Desktop.
Save spastorino/6873dc7f371fb0fa7651 to your computer and use it in GitHub Desktop.
Rust by example - http://rustbyexample.com/bounds.html issues
use std::ops::{Add, Sub, Mul};
#[derive(Show, Copy)]
struct Vec2<T> {
x: T,
y: T,
}
// Apply bound to `T` at first instance of `T`. `T`
// must implement the `Add` trait.
impl<T: Add<T>> Add<Vec2<T>>
for Vec2<T> {
type Output = Vec2<T>;
fn add(self, rhs: Vec2<T>) -> Vec2<T> {
Vec2 {
// `x` and `y` are of type `T`, and implement the `add` method
x: self.x.add(rhs.x),
// The sugary `+` operator can also be used
y: self.y + rhs.y,
}
}
}
// Bound: `T` must implement the `Sub` trait
impl<T> Sub<Vec2<T>> for Vec2<T>
where T: Sub<T> {
type Output = Vec2<T>;
fn sub(self, rhs: Vec2<T>) -> Vec2<T> {
Vec2 {
x: self.x - rhs.x,
y: self.y - rhs.y,
}
}
}
// Bound: `T` must implement *both* the `Add` trait and the `Mul` trait
impl<T> Vec2<T>
where T: Add<T> + Mul<T> {
fn dot(self, rhs: Vec2<T>) -> T {
(self.x * rhs.x) + (self.y * rhs.y)
}
}
fn main() {
// Floats implement the `Add`, `Mul` and `Sub` traits
let v1 = Vec2 { x: 1.2_f32, y: 3.4 };
let v2 = Vec2 { x: 5.6_f32, y: 7.8 };
println!("{} + {} = {}", v1, v2, v1 + v2);
println!("{} - {} = {}", v1, v2, v1 - v2);
println!("{} â‹… {} = {}", v1, v2, v1.dot(v2));
// Error! `char` doesn't implement the `Add` trait
//println!("{}", Vec2 { x: ' ', y: 'b' } + Vec2 { x: 'c', y: 'd' });
// FIXME ^ Comment out this line
}
bounds.rs:16:9: 21:10 error: mismatched types: expected `Vec2<T>`, found `Vec2<<T as core::ops::Add>::Output>` (expected type parameter, found associated type)
bounds.rs:16 Vec2 {
bounds.rs:17 // `x` and `y` are of type `T`, and implement the `add` method
bounds.rs:18 x: self.x.add(rhs.x),
bounds.rs:19 // The sugary `+` operator can also be used
bounds.rs:20 y: self.y + rhs.y,
bounds.rs:21 }
bounds.rs:31:9: 34:10 error: mismatched types: expected `Vec2<T>`, found `Vec2<<T as core::ops::Sub>::Output>` (expected type parameter, found associated type)
bounds.rs:31 Vec2 {
bounds.rs:32 x: self.x - rhs.x,
bounds.rs:33 y: self.y - rhs.y,
bounds.rs:34 }
bounds.rs:42:9: 43:6 error: binary operation `+` cannot be applied to type `<T as core::ops::Mul>::Output`
bounds.rs:42 (self.x * rhs.x) + (self.y * rhs.y)
bounds.rs:43 }
error: aborting due to 3 previous errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment