【问题标题】:Rust String is not a String [duplicate]Rust 字符串不是字符串 [重复]
【发布时间】:2017-04-10 14:05:53
【问题描述】:

我使用 String::from("string") 来获取字符串

let dog = String::from("dog")

dog == String::from("dog")

返回假。即使在模式匹配中。

match dog.as_ref() {
   "dog" => println!("Dog is a dog"), //no output
   _ => println!("Dog is not a dog")
}

怎么了?

例子

use std::io;
fn main() {
    let mut sure = String::from("");
    println!("Hello, world!");
    println!("Are you sure(Y/N)"); 
    io::stdin().read_line(&mut sure).expect("Failed");
    println!("sure {}", sure ); 
    let surely = {sure == String::from("Y")};
    println!("surely {} ", surely ); //this line output is "surely false"
    if surely {
        dog_loop("HA");
    }
}

【问题讨论】:

标签: string rust


【解决方案1】:

作为一般规则,在 Rust 中比较字符串时,最好将字符串转换为 &str 以与字符串文字进行比较,而不是将字符串文字转换为 String。原因是后者需要创建对象(分配给String),而第一个不需要,因此效率更高。

您在此处看到的具体问题来自您的输入没有去除多余的空格这一事实。行后

io::stdin().read_line(&mut sure).expect("Failed");

sure 的值不是您可能期望的"Y",但实际上是 Unix 上的 "Y\n" 或 Windows 上的 "Y\r\n"。您可以通过如下修改比较来直接进行比较:

let surely = {sure.as_str() == "Y\n"};
println!("surely {} ", surely );

你会看到它返回“肯定是真的”。但是,这会使您的代码依赖于平台。最好使用字符串方法String.trim(),这将删除尾随空格。

【讨论】:

  • 我建议不要与"Y\n" 进行比较,因为它会使代码更加依赖于平台,并且可能是一个隐藏的混淆源。 trim() 在我看来绝对是要走的路,就像重复问题的答案所示。
  • 感谢您指出这一点。更新澄清。
猜你喜欢
  • 2015-08-23
  • 2019-12-22
  • 1970-01-01
  • 1970-01-01
  • 2010-09-12
  • 2020-04-20
  • 2013-02-28
  • 2021-10-18
相关资源
最近更新 更多