Skip to content

Instantly share code, notes, and snippets.

@AmanRaj1608
Created January 6, 2025 19:48
Show Gist options
  • Save AmanRaj1608/1683a63dc7fea977763b51846f88dbca to your computer and use it in GitHub Desktop.
Save AmanRaj1608/1683a63dc7fea977763b51846f88dbca to your computer and use it in GitHub Desktop.
#[derive(Debug)]
struct Point3d {
x: i32,
y: i32,
z: i32,
}
#[derive(Debug)]
struct Point2d {
x: i32,
y: i32,
}
// enum way you described on the call
enum Point {
ThreeD(Point3d),
TwoD(Point2d),
}
fn enum_way() {
let points = vec![
Point::ThreeD(Point3d { x: 1, y: 2, z: 3 }),
Point::TwoD(Point2d { x: 4, y: 5 }),
];
for point in points {
match point {
Point::ThreeD(p) => println!("x={}, y={}, z={}", p.x, p.y, p.z),
Point::TwoD(p) => println!("x={}, y={}", p.x, p.y),
}
}
}
// generic trait with single vector approach
trait Coordinate {
fn get_coordinates(&self) -> Vec<i32>;
}
impl Coordinate for Point3d {
fn get_coordinates(&self) -> Vec<i32> {
vec![self.x, self.y, self.z]
}
}
impl Coordinate for Point2d {
fn get_coordinates(&self) -> Vec<i32> {
vec![self.x, self.y]
}
}
fn generic_way() {
let points: Vec<Box<dyn Coordinate>> = vec![
Box::new(Point3d { x: 1, y: 2, z: 3 }),
Box::new(Point2d { x: 4, y: 5 }),
Box::new(Point2d { x: 6, y: 7 }),
];
for point in points {
println!("{:?}", point.get_coordinates());
}
}
// typescript kind of way to use optional param
#[derive(Debug)]
struct UnifiedPoint {
x: i32,
y: i32,
z: Option<i32>,
}
fn unified_way() {
let points = vec![
UnifiedPoint { x: 1, y: 2, z: Some(3) },
UnifiedPoint { x: 4, y: 5, z: None },
UnifiedPoint { x: 12, y: 2, z: Some(9) },
];
for p in points {
match p.z {
Some(z) => println!("x={}, y={}, z={}", p.x, p.y, z),
None => println!("x={}, y={}", p.x, p.y),
}
}
}
fn main() {
enum_way();
print!("\n\n");
generic_way();
print!("\n\n");
unified_way();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment