How to write "not if let"?

I want check if “enum” not match some pattern, and in that case return error.
Result of match not interesting for me, at now I wrote:

    if let Some(&TokenTree::Token(_, Token::Semi)) = {
    } else {
        return Err("expect ';' here".to_string());

I dislike empty if part, idealy I want write something like this:

  if not (let Some(&TokenTree::Token(_, Token::Semi)) = {
      return Err("expect ';' here".to_string());

I something like this possible?


The solution for this would be “if let Err(err) = …”


For Option and Result, there are helper methods for this:

  if {
    // code 
  if ret.is_err() {
    // code

It looks like you have several enums nested together though, in which case neither of the prior solutions really solve your specific problem. There’s no syntax for “does not match this one pattern.”

I would recommend using a match rather than if let else, though, because I think its less confusing:

match {
     Some(&TokenTree::Token(_, Token::Semi)) => { }
     _ => return Error("expect ';' here".to_string())

You might also leave a comment in the ‘ok’ block to explain why its empty.


Has there ever been any thoughts to having a guard let else syntax in Rust, similar to what is in Swift?

1 Like

It looks bad to me. This is not a part of Swift I’d like to see copied in Rust.

If you want to copy in Rust something from Swift, then I’d like parts like this:

That is, overflow checks removals, escape analysis to remove some boxing and heap allocation of objects and strings, devirtualization of some trait object usage, array bound test removals, and more of the same.


I disagree.

This is succient and powerful and common.

Mhm, I think I would like a mightier if let syntax in general. ‘if let … && …’ and so on. Or, in this case, if !let …
If let is sufficient most of the times, but feels somewhat restricted sometimes, and i don’t feel the need for that

1 Like

maybe we need this pattern:

fn multiply(first_number_str: &str, second_number_str: &str) -> Result<i32, ParseIntError> {
    let first_number = match first_number_str.parse::<i32>() {
        Ok(first_number)  => first_number,
        Err(e) => return Err(e),

    let second_number = match second_number_str.parse::<i32>() {
        Ok(second_number)  => second_number,
        Err(e) => return Err(e),

    Ok(first_number * second_number)

ref: Early returns - Rust By Example

There is the matches! macro now, so there is no need for additional syntax. You can write if !matches!(x, pattern) { … }.

1 Like

I find "if let None" is readable and works.

fn main() {
    let  nothing:Option<String> = None;
    if let None = nothing {

Guys, this thread is four years old. If you want to have a new discussion on the same topic, open a new thread.