Comparing string in Rust

后端 未结 1 1959
挽巷
挽巷 2020-12-31 08:25

I want to compare a string input from stdin to a static string with no luck.

Here is what I have tried so far:

fn main() -> () {
    let mut line          


        
1条回答
  •  一整个雨季
    2020-12-31 08:50

    First of all, the line contains the line terminator. You probably want to use trim (or one of its variants) to ignore that.

    Secondly, you're doing a lot of unnecessary conversions and allocations. Try to avoid those.

    Third, to_string is (or at least, was the last time I checked) inefficient due to over-allocation. You want into_string.

    Fourth, the quickest way to go from a String to a &str is to "cross-borrow" it; given a String s, &*s will re-borrow it as a &str. This is because a String implements Deref<&str>; in other words, String acts kind of like a smart pointer to a borrowed string, allowing it to decay into a simpler form.

    Fifth, unless you're doing something unusual, you can rewrite this as a for loop using the lines iterator method.

    Sixth, be aware that stdin() actually allocates a new buffered reader every time you call it. Not only that, but characters read into the buffer do not get "pushed back" into STDIN when a new buffer is created; that data is simply lost. So you really don't want to be calling it in a loop. If you need to, call it once and keep the result in a variable.

    So, I end up with this:

    fn main() {
        for line in std::io::stdin().lines() {
            // Extract the line, or handle the error.
            let line = match line {
                Ok(line) => line,
                Err(err) => panic!("failed to read line: {}", err)
            };
    
            assert_eq!(line.trim(), "exit");
        }
    }
    

    0 讨论(0)
提交回复
热议问题