简体   繁体   中英

Is it possible to unpack a generic tuple via pattern matching in Rust?

It is possible to perform the following:

fn foo((a, b): (i32, f32)) {
  unimplemented!();
}

and it can be executed via:

let ab = (1, 2.0);
foo(ab);

In effect ab is unpacked into a and b separately.

I'd like to do something similar with generics.

pub struct QuadTree<(Kx, Ky), V> {
  ...
}

Whether this is useful or not I'm not sure how to get this to compile. Ideally I'd like to be able to call something like this:

struct Point(i32, i32);    

...

let quad_tree: QuadTree<Point, String> = QuadTree::new();

Would this be possible on Rust nightly without macros?

You probably want the following:

pub struct QuadTree<GenericPoint, V> {
  ...
}

Then, you could require (via a trait) that GenericPoint offers an x- and a y-acceessor. Possibly you would also require GenericPoint to define type aliases for Kx and Ky .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM