匹配可选字符串时,预期字符串,找到和str

zef*_*ciu 11 pattern-matching rust

我正在尝试在Rust中编写一个简单的函数,它将询问用户一个期待回答"你"或"我"的问题.它应该返回一个布尔值,或者再次询问用户是否回答错误.我提出了:

fn player_starts() -> bool {                                                    
    println!("Who will start (me/you)");                                       
    loop {                                                                      
        let input = readline::readline(">");                                    
        match input {                                                           
            Some("me") => return true,                                          
            Some("you") => return false,                                        
            _ => None,                                                          
        }                                                                          
    }                                                                           
}       
Run Code Online (Sandbox Code Playgroud)

我得到的是:

error: mismatched types:
 expected `collections::string::String`,
    found `&'static str`
(expected struct `collections::string::String`,
found &-ptr) [E0308]
Run Code Online (Sandbox Code Playgroud)

有没有办法强迫文字在这里工作,还是有更好的方法来实现我的目标?

fjh*_*fjh 13

这应该工作:

fn player_starts() -> bool {                      
    println!("Who will start me/you)");                    
    loop {
        let input = readline::readline(">");
        match input.as_ref().map(String::as_ref) {
            Some("me") => return true,
            Some("you") => return false,
            _ => ()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意match语句中的表达式,我们将其从a转换Option<String>为an Option<&str>.


Tar*_*ama 9

通常将a转换&str为a的方式Stringto_owned,例如

"me".to_owned()
Run Code Online (Sandbox Code Playgroud)

但是,你不能在a上进行模式匹配String.你可以expect成功的,得到了&strString上那么模式匹配:

fn player_starts() -> bool {                                                    
    println!("Who will start (me/you)");                                       
    loop {                                                                      
        let input = readline::readline(">");
        match input.expect("Failed to read line").as_ref() {
            "me" => return true,                                          
            "you" => return false,
            _ => println!("Enter me or you"),
        }                                                                          
    }                                                                           
}
Run Code Online (Sandbox Code Playgroud)

  • 使用 `to_owned()` 或 `into()`(如果目标类型已知)而不是 `to_string()` 更为惯用。后者通过 `Display` trait 工作,它调用格式化代码,这会引入一些开销。也许如果 Rust 获得 impl 专业化,这可以解决,但我们还没有。 (2认同)
  • @TartanLlama我的回答是,如果`input`是'None`,它对我来说似乎非常有用,它会感到恐慌.(但不是低估你) (2认同)