2016-11-26 112 views
0

我用String ::從( 「串」)得到一個字符串鏽字符串不是字符串

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

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

返回false。即使在模式匹配。

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

無法在[Rust Playground]中重現(https://play.rust-lang.org/?gist=5e1f563dd638e1358f409e07c8d7931c&version=stable&backtrace=0)。你可以創建一個[mcve]嗎? – Aurora0001

+0

現在編輯。我添加了例子。 –

回答

1

作爲一般規則,在鏽比較字符串時,最好把串入一個&str針對字符串比較文字,而不是轉換字符串文字成String。原因是後者需要創建對象(分配String),而第一個不需要,所以效率更高。

你在這裏看到的具體問題來自於你的輸入沒有多餘的空格被去除的事實。行

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

後的sure值不"Y"如你所料,但實際上"Y\n"是Unix或"Y\r\n"在Windows上。你可以直接通過修改你的比較來比較它:

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

你會看到它返回「肯定是真的」。但是,這會使您的代碼與平臺相關。最好使用字符串方法String.trim(),這將刪除尾隨的空白。

+1

我建議不要與'「Y \ n」'比較,因爲它會使代碼更依賴於平臺,並且可能是一個隱藏的混淆源。 'trim()'絕對是我認爲的方式,就像重複問題的答案一樣。 – Aurora0001

+1

謝謝你指出。更新澄清。 –