我正在尝试制作hang子手游戏:
use std::io::stdin;
fn main() {
let mut isRunning: bool = true;
'outer: loop {
let w1 = vec!['m', 'o', 'm', 'm', 'y']; //the answer
println!("Guess a Character");
loop {
let mut line = String::new(); //the guess
let input = stdin().read_line(&mut line);
let char_vec: Vec<char> = line.to_string().chars().collect();
for x in 0..4 {
if line == w1[x] {
println!("you guessed right? ");
}
}
}
}
}
将用户输入与单词中的字母进行比较时,出现编译器错误:
error[E0277]: the trait bound `std::string::String: std::cmp::PartialEq<char>` is not satisfied
--> src/main.rs:17:25
|
17 | if line == w1[x] {
| ^^ can't compare `std::string::String` with `char`
|
= help: the trait `std::cmp::PartialEq<char>` is not implemented for `std::string::String`
为什么这不能按预期工作?
答案 0 :(得分:1)
这是错误消息的关键部分:
can't compare `std::string::String` with `char`
问题是您将用户输入存储为String
,但试图将其与char
进行比较。有两种解决方案。也许最简单的方法是使用用户输入char
中的第一个String
:
use std::io::stdin;
fn main() {
'outer: loop {
let w1 = vec!['m', 'o', 'm', 'm', 'y']; //the answer
println!("Guess a Character");
loop {
let mut line = String::new(); //the guess
stdin().read_line(&mut line).unwrap();
if line.len() < 1 || line.len() > 1 {
println!("Please guess a single char.");
} else {
let guess = line.chars().next().unwrap();
let mut correct = false;
for c in &w1 {
if guess == *c {
correct = true;
break;
}
}
if correct {
println!("You guessd right!");
} else {
println!("You guessed wrong...");
}
}
}
}
}