Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from Reverse()?

Tags:

rust

I'm trying MinHeap from std::BinaryHeap like

use std::collections::BinaryHeap;
use std::cmp::Reverse;

let mut heap = BinaryHeap::new();

heap.push(Reverse(1));
heap.push(Reverse(5));
heap.push(Reverse(2));

assert_eq!(heap.pop(), Some(Reverse(1)));
assert_eq!(heap.pop(), Some(Reverse(2)));
assert_eq!(heap.pop(), Some(Reverse(5)));
assert_eq!(heap.pop(), None);

But allow varibles from heap.pop() or heap.peek() is Reverse() type, which is not easy to use, how to get value from it?

like image 973
voddle Avatar asked Oct 24 '25 16:10

voddle


1 Answers

From the docs we can see that Reverse is a tuple and its only field is public:

pub struct Reverse<T>(pub T);

This means we can access the field with .0 Like this:

let reversed = Reverse(42);
assert_eq!(reversed.0, 42);
like image 90
mhutter Avatar answered Oct 26 '25 05:10

mhutter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!