0

I am trying to use a match with user inputs from the command line to create a simple interface for a program.

Here is the relevant code:

let NEW_BLOCK: String = String::from("NEW_BLOCK");
let ADD_BLOCK: String = String::from("ADD_BLOCK");
let PRINT_CHAIN: String = String::from("PRINT_CHAIN");
let PUBLISH: String = String::from("PUBLISH");

let input = String::from("some input");

match input {
    NEW_BLOCK => {
        println!("inside NEW_BLOCK");
    },
    ADD_BLOCK => {
        println!("inside ADD_BLOCK");
    },
    PRINT_CHAIN => {
        println!("inside PRINT_CHAIN");
    },
    PUBLISH => {
        println!("inside PUBLISH");
    },
    _ => {
        println!("Inside else");
    },
}

Permalink to the playground

This produces a few warnings such as:

warning: unreachable pattern
  --> src/main.rs:13:9
   |
10 |         NEW_BLOCK => {
   |         --------- matches any value
...
13 |         ADD_BLOCK => {
   |         ^^^^^^^^^ unreachable pattern
   |
   = note: `#[warn(unreachable_patterns)]` on by default

No matter the value of input, I always go into the NEW_BLOCK arm. In general, I always go into the first arm of the match operator. I don't know why.

My best guess is that the comparison that match is using is only comparing the types. But I don't think this is a very good guess.

Does anyone know why this is happening? Thank you in advance for the help :)

(By the way, a found workaround using string slices. However, I'd like to know why using Strings isn't working).

mcarton
  • 27,633
  • 5
  • 85
  • 95

1 Answers1

0

I think it got to do with fact that named variables match any value and considered irrefutable patterns. You need to put in refutable patterns to make it work correctly.

First of all, there are some syntax and logic issues. Once, you fix it you will get warning like:

"Matches any values".

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=25bc0745c2d4dbb2ab86a44075a5fe0d

apatniv
  • 1,771
  • 10
  • 13