2

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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Mazeryt
  • 855
  • 1
  • 18
  • 37
  • [Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?](https://stackoverflow.com/q/40006219/155423) – Shepmaster Apr 14 '19 at 20:38
  • Hmm, yes in my code I used: &out[out.find(SECTION_TEST).unwrap()+SECTION_TEST.len()..] Just posted simplified version, which as you mentioned wont compile. Is that construction ok? I am just reading the link that you have sent – Mazeryt Apr 14 '19 at 20:43

2 Answers2

7

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
3

For those unable to change the static to a const—although it's a little convoluted—another option is to use an if statement, which will return the &str (or whatever is defined) that lives in the static's NAME:

static STATUS_TEST_OK: &str = "PASSED";

fn match_out(s: &str) -> bool {

    match s {
        str if str == STATUS_TEST_OK => {
            println!("Yes");
            true
        }
        _ => {
            println!("No");
            false
        }
    }
}
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Guest
  • 31
  • 2
  • 1
    The technical term for such `if` statement is a [match guard](https://doc.rust-lang.org/reference/expressions/match-expr.html#match-guards). – Chayim Friedman Jun 08 '22 at 01:07