Skip to content

Instantly share code, notes, and snippets.

@kriogenia
Last active June 17, 2022 16:44
Show Gist options
  • Save kriogenia/e9d657beab383e3e35ab89680048c2b8 to your computer and use it in GitHub Desktop.
Save kriogenia/e9d657beab383e3e35ab89680048c2b8 to your computer and use it in GitHub Desktop.
Dynamic tuple access in Rust
use std::{rc::Rc, cell::RefCell};
macro_rules! nth {
($tuple:expr, $axis:tt) => {
match $axis {
0 => $tuple.0,
1 => $tuple.1,
_ => unreachable!()
}
}
}
struct Limit {
vector: Rc<RefCell<(i32, i32)>>,
limit: i32,
axis: u8
}
impl Limit {
fn is_out(&self) -> bool {
let axis = self.axis;
nth!((*self.vector).borrow(), axis) > self.limit
}
}
fn main() {
let vecref = Rc::new(RefCell::new((0, 0)));
let limit_x = Limit { vector: vecref.clone(), limit: 250, axis: 0 };
let limit_y = Limit { vector: vecref.clone(), limit: 800, axis: 1 };
for _ in 0..5 {
vecref.borrow_mut().0 += 100;
vecref.borrow_mut().1 += 200;
if limit_x.is_out() || limit_y.is_out() {
println!("Position {:?} is out of bounds. Resetting position", vecref);
*vecref.borrow_mut() = (0,0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment