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>.
通常将a转换&str为a的方式String是to_owned,例如
"me".to_owned()
Run Code Online (Sandbox Code Playgroud)
但是,你不能在a上进行模式匹配String.你可以expect成功的,得到了&str从String上那么模式匹配:
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)
| 归档时间: |
|
| 查看次数: |
7666 次 |
| 最近记录: |