patternrustModerate
Expected String, found &str when matching an optional string
Viewed 0 times
foundmatchingexpectedstroptionalwhenstring
Problem
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:
What I get is:
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 {
Some("me") => return true,
Some("you") => return false,
_ => None,
}
}
}What I get is:
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?
Solution
This should work:
Note the expression in the match statement, where we convert from an
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,
_ => ()
}
}
}Note the expression in the match statement, where we convert from an
Option to an Option.Code Snippets
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,
_ => ()
}
}
}Context
Stack Overflow Q#32500974, score: 28
Revisions (0)
No revisions yet.