EN VI

Rust - How to compare a value in struct using match?

2024-03-12 11:30:04
Rust - How to compare a value in struct using match

I would like to replace my if case with match case

struct Point {
    x: i32,
}

fn main() {
    let p = Point { x: 0 };
    let q = Point { x: 0 };
    
    if p.x == q.x {
        println!("p and q have same x: {0}", p.x);
    } else {
        println!("p and q doesn't have same x value");
    }
    
    // match p.x {
    //     q.x => println!("p and q have same x: {0}", p.x),
    //     _ => println!("On neither axis"),
    // }
}

which run normally. However when I uncomment my code snippet in the code an error would occur.

error: expected one of `,`, `=>`, `@`, `if`, `|`, or `}`, found `.`
  --> src/main.rs:16:10
   |
16 |         q.x => println!("p and q have same x: {0}", p.x),
   |          ^ expected one of `,`, `=>`, `@`, `if`, `|`, or `}`

Not sure how to fix it

Solution:

Only const values can be compared, and there is no way to transform a non-const variable into const. However, a guard expression can be used.

match p.x {
    v if p.x == q.x => println!("p and q have same x: {0}", v),
    _ => println!("On neither axis"),
}
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login