2015-07-21 143 views
3

在學習Rust的練習中,我正在嘗試一個簡單的程序來接受你的名字,然後打印你的名字,如果它是有效的。如何匹配從標準輸入讀取的字符串?

只有「Alice」和「Bob」是有效名稱。

use std::io; 

fn main() { 
    println!("What's your name?"); 
    let mut name = String::new(); 

    io::stdin().read_line(&mut name) 
    .ok() 
    .expect("Failed to read line"); 

    greet(&name); 
} 

fn greet(name: &str) { 
    match name { 
     "Alice" => println!("Your name is Alice"), 
     "Bob" => println!("Your name is Bob"), 
     _ => println!("Invalid name: {}", name), 
    } 
} 

當我cargo run這個main.rs文件,我得到:

What's your name? 
Alice 
Invalid name: Alice 

現在,我的猜測是,因爲 「愛麗絲」 是&'static str型和name&str型的,也許它不匹配正確...

+2

嘗試'match name.trim(){...}'。我目前無法測試,但我敢打賭,輸入中有一個換行符。 –

+0

就是這樣......我總是忘記這一點,謝謝!如果你發佈答案,我會贊成並接受。 – sircapsalot

+0

相關,雖然不*完全*重複:https://stackoverflow.com/questions/27201086/comparing-string-in-rust/27201198#27201198 –

回答

6

我敢打賭,它不是由類型不匹配造成的。我把我的賭注放在那裏有一些不可見的字符(在這種情況下是新行)。爲了實現你的目標,你應該修整你的輸入字符串:

match name.trim() { 
    "Alice" => println!("Your name is Alice"), 
    "Bob" => println!("Your name is Bob"), 
    _ => println!("Invalid name: {}", name), 
} 
+0

A.B.尚未提交答案,所以我只接受你的答案。 – sircapsalot

相關問題