Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a string against a static &str?

I am writing a program that does probably a little bit too much with string processing. I moved most of the literal messages to constants; I'm not sure if that is the proper way in Rust, but I'm used to writing that in C.

I figured out that I cannot easily use my static &str inside a match expression. I can use the text itself, but cannot figure out how to do that properly.

I understand it's a compiler issue, but don't know how to write that construction properly in Rust style. Should I use enums instead of C-like static variables?

static SECTION_TEST: &str = "test result:";
static STATUS_TEST_OK: &str = "PASSED";

fn match_out(out: &String) -> bool {
    let s = &out[out.find(SECTION_TEST).unwrap() + SECTION_TEST.len()..];

    match s {
        STATUS_TEST_OK => {
            println!("Yes");
            true
        }
        _ => {
            println!("No");
            false
        }
    }
}
error[E0530]: match bindings cannot shadow statics
 --> src/lib.rs:8:9
  |
2 | static STATUS_TEST_OK: &str = "PASSED";
  | --------------------------------------- the static `STATUS_TEST_OK` is defined here
...
8 |         STATUS_TEST_OK => {
  |         ^^^^^^^^^^^^^^ cannot be named the same as a static
like image 216
Mazeryt Avatar asked Oct 16 '25 08:10

Mazeryt


1 Answers

Use a constant instead of a static:

const STATUS_TEST_OK: &str = "PASSED";

fn match_out(s: &str) -> bool {
    match s {
        STATUS_TEST_OK => {
            println!("Yes");
            true
        }
        _ => {
            println!("No");
            false
        }
    }
}

See also:

  • What is the difference between a const variable and a static variable and which should I choose?
  • What is the difference between immutable and const variables in Rust?
  • How to match a String against string literals in Rust?
  • Why is this match pattern unreachable when using non-literal patterns?
like image 186
Shepmaster Avatar answered Oct 18 '25 23:10

Shepmaster



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!