预期字符串,匹配可选字符串时找到 &str [英] Expected String, found &str when matching an optional string
本文介绍了预期字符串,匹配可选字符串时找到 &str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 Rust 中编写一个简单的函数,它会询问用户一个问题,期望得到你"或我"的回答.如果用户回答错误,它应该返回一个布尔值或再次询问.我想出了:
I am trying to write a simple function in Rust that will ask user a question expecting answer of "you" or "me". It should return a boolean value or ask again if the user answers wrong. I came up with:
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,
}
}
}
我得到的是:
error: mismatched types:
expected `collections::string::String`,
found `&'static str`
(expected struct `collections::string::String`,
found &-ptr) [E0308]
有什么方法可以强制文字在这里起作用,或者有什么更好的方法来实现我的目标?
Is there some way to coerce the literal to work here or is there some better way to achieve my goal?
推荐答案
这应该有效:
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,
_ => ()
}
}
}
注意 match 语句中的表达式,我们将其中的 Option
转换为 Option<&str>
.
Note the expression in the match statement, where we convert from an Option<String>
to an Option<&str>
.
这篇关于预期字符串,匹配可选字符串时找到 &str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文