且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

比较 Rust 中的字符串

更新时间:2023-11-14 23:21:58

首先,该行包含行终止符.您可能想使用 trim(或其变体之一)来忽略它.

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.

第三,由于过度分配,to_string(或者至少,我最后一次检查)效率低下.你想要into_string.

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

第四,从 String&str 的最快方法是交叉借用"它;给定一个 String s&*s 会将它作为 &str 重新借用.这是因为 String 实现了 Deref;换句话说,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.

第五,除非您正在做一些不寻常的事情,否则您可以使用 lines 迭代器方法将其重写为 for 循环.

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

第六,请注意 stdin() 实际上每次调用时都会分配一个新的缓冲读取器.不仅如此,当创建新缓冲区时,读入缓冲区的字符不会被推回"到标准输入中;该数据只是丢失了.所以你真的不想在循环中调用它.如果需要,请调用一次并将结果保存在变量中.

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