String Comparison in Rust

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

Here is what I have tried so far:

fn main() -> () { let mut line = "".to_string(); let exit = "exit".to_string(); while line.as_slice() != exit.as_slice() { let input = std::io::stdin().read_line().ok(); line.push_str( input.unwrap().to_string().as_slice() ); assert_eq!(line, exit); } } 

However, during the approval, he failed. How to compare string input with static string in Rust?

Your help is greatly appreciated.

+6
source share
1 answer

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

Secondly, you do a lot of unnecessary transformations and distributions. Try to avoid this.

Thirdly, to_string (or at least the last time I checked) is inefficient due to redistribution. You want into_string .

Fourth, the fastest way to go from String to &str is to "intercept" it; if a String s , &*s will borrow it as &str . This is because String implements Deref<&str> ; In other words, String acts as a smart pointer to a borrowed string, allowing it to fade out in a simpler form.

Fifth, if you are not doing something unusual, you can rewrite it as a for loop using the iterator lines method.

Sixth, remember that stdin() actually allocates a new buffered reader every time you call it. Not only that, but characters read in the buffer are not β€œdiscarded” in STDIN when creating a new buffer; that the data is simply lost. So you really don't want to be called in a loop. If you need, name it once and save the result in a variable.

So, I get the following:

 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"); } } 
+12
source

Source: https://habr.com/ru/post/978861/


All Articles