Search code examples
rustbooleancontains

how to bool a string contains a digit between an another digit


I want to know if it possible to boolean a String contains a digit between an another digit to set a variable after

the code i tried

pub fn ram() -> String {
    let okmdr = Command::new("wmic").arg("memorychip").arg("get").arg("speed").output().unwrap_or_else(|e| panic!("impossible d'obtenir le type et la vitesse de la RAM"));
    let speed = String::from_utf8_lossy(&okmdr.stdout).to_string();
    let split: Vec<String> = speed.split_inclusive("Speed").map(|s| s.to_string()).collect();
    let splitjsp: Vec<String> = split[1].split(" ").map(|o| o.to_string()).collect();
    let jsp = if splitjsp[2].contains(1601..3200) { String::from("DDR4") } else if splitjsp[2].contains(0..1600) { String::from("DDR3") } else { String::from("Unknown")};
    jsp
}

the error i got :

let jsp = if splitjsp[2].contains(1601..3200) { String::from("DDR4") } else if splitjsp[2].contains(0..1600) { String::from("DDR3") }...
                         -------- ^^^^^^^^^^ expected an `FnMut<(char,)>` closure, found `std::ops::Range<{integer}>`
                         |
      required by a bound introduced by this call

Solution

  • Your English is a bit garbled, so let me see if I got that right: You want to check if some number is contained in an interval, but that number is currently stored in a string?

    Well, currently your code is calling str::contains which can check whether a string contains e.g. a substring or character. For example, you can test whether "sd" is contained in "asdf" (yes). That is not what you want.

    You'll have to use

    Do note that a Rust range a..b contains a, but doesn't contain b. If you want a range that contains both ends, you want a..=b.

    So you might do something like:

    let jsp2 = splitjsp[2].parse().expect("JSP output format: expected integer in line 3");
    if (1601..=3200).contains(&jsp2) {
        …
    

    but it might be more elegant to use a match:

    match jsp2 {
        0..1601 => …,
        1601..3201 => …,
        _ => …,
    }
    

    Playground