Skip to content

Instantly share code, notes, and snippets.

@SiegeLord
Created June 11, 2014 11:53
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 SiegeLord/e09c32b8cf2df72b2422 to your computer and use it in GitHub Desktop.
Save SiegeLord/e09c32b8cf2df72b2422 to your computer and use it in GitHub Desktop.
Rust matrix moving via refcell
clone
move
move
[100, 200, 300]
use std::cell::RefCell;
struct Matrix
{
data: RefCell<Option<Vec<f32>>>
}
impl Mul<f32, Matrix> for Matrix
{
fn mul(&self, r: &f32) -> Matrix
{
println!("move");
let mut data = self.data.borrow_mut().take().unwrap();
for v in data.mut_iter()
{
*v *= *r;
}
Matrix{ data: RefCell::new(Some(data)) }
}
}
impl<'l> Mul<f32, Matrix> for &'l Matrix
{
fn mul(&self, r: &f32) -> Matrix
{
println!("clone");
let mut data = self.data.borrow().get_ref().clone();
for v in data.mut_iter()
{
*v *= *r;
}
Matrix{ data: RefCell::new(Some(data)) }
}
}
fn main()
{
let m = Matrix{ data: RefCell::new(Some(vec![1.0f32, 2.0, 3.0])) };
let m2 = &m * 2.0 * 5.0 * 10.0;
println!("{}", m2.data.borrow().get_ref());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment