Eloff
Eloff

Reputation: 21656

Just get a boolean result from "if let"?

Is there a more concise way to write this?

   let neg = if let Some(b'-') = self.peek() {
        true
   } else {
        false
   };

Where peek() returns an Option<u8>, if it wasn't clear from the code above.

Upvotes: 4

Views: 399

Answers (2)

loganfsmyth
loganfsmyth

Reputation: 161457

The other answer is accurate for the specific example because of Eq, but I'll answer in the general case.

Rust now has a matches! macro for this usecase, so you can also write

let neg = matches!(self.peek(), Some(b'-'));

if you don't want to or are unable to use Eq.

Upvotes: 4

jtbandes
jtbandes

Reputation: 118671

Since Option derives an implementation for Eq, you can simply write:

let neg = Some(b'-') == self.peek();

Upvotes: 3

Related Questions