Skip to content

Instantly share code, notes, and snippets.

@greyblake
Created August 28, 2016 18:27
Show Gist options
  • Save greyblake/55b69f4bac29071f6355566339a0a2ec to your computer and use it in GitHub Desktop.
Save greyblake/55b69f4bac29071f6355566339a0a2ec to your computer and use it in GitHub Desktop.
use std::ops::Mul;
#[derive(Debug)]
struct Vector {
x : f64,
y : f64
}
impl<'a> Mul<f64> for &'a Vector {
type Output = Vector;
fn mul(self, k : f64) -> Vector {
Vector { x: self.x * k, y: self.y * k }
}
}
impl<'a> Mul<i32> for &'a Vector {
type Output = Vector;
fn mul(self, k : i32) -> Vector {
let k = k as f64;
Vector { x: self.x * k, y: self.y * k }
}
}
fn main() {
let v = Vector { x: 1.0, y: 2.0 };
let v2 = &v * 1.5;
let v3 = &v * 3;
println!("{:?}", v2);
println!("{:?}", v3);
}
@zekefast
Copy link

use std::ops::Mul;

#[derive(Debug)]
#[derive(Clone)]
#[derive(Copy)]
struct Vector {
    x : f64,
    y : f64
}

impl Mul<f64> for Vector {
    type Output = Vector;

    fn mul(self, k: f64) -> Self::Output {
        Vector { x: self.x * k, y: self.y * k }
    }
}

impl Mul<i32> for Vector {
    type Output = Vector;

    fn mul(self, k: i32) -> Self::Output {
        return self * k as f64;
    }
}

fn main() {
    let v = Vector { x: 1.0, y: 2.0 };
    let v2 = v * 1.5;
    let v3 = v * 3;

    println!("{:?}", v2);
    println!("{:?}", v3);
}

If you don't mind of copy things a bit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment