想法是发送一组向量的字符,让函数显示当前正确的猜测。
这是我的主要内容:
fn main() {
let mut guessedLetters = vec![];
displayWord(guessedLetters);
}
函数如下:
fn displayWord(correctGuess: Vec<char>) {
let mut currentWord = String::new();
for x in 0..5 {
currentWord.push(correctGuess[x]);
}
println!("Current guesses: {}", currentWord);
}
我不知道我应该在 displayWord
的参数中写什么。
最佳答案
您的代码有几个问题。
第一个错误非常简单:
--> src/main.rs:38:25
|
38 | displayWord(guessed_Letters);
| ^^^^^^^^^^^^^^^ expected char, found enum `std::option::Option`
|
= note: expected type `std::vec::Vec<char>`
found type `std::vec::Vec<std::option::Option<char>>`
您编写的函数需要一个字符向量...但您向它传递了一个向量 Option<char>
.这是发生在这里:
guessed_Letters.push(line.chars().nth(0));
According to the documentation , nth
方法返回 Option
.这里的快速修复是 unwrap
Option
获取潜在值(value):
guessed_Letters.push(line.chars().nth(0).unwrap());
你的下一个错误是:
error[E0382]: use of moved value: `guessed_Letters`
--> src/main.rs:38:25
|
38 | displayWord(guessed_Letters);
| ^^^^^^^^^^^^^^^ value moved here in previous iteration of loop
|
= note: move occurs because `guessed_Letters` has type `std::vec::Vec<char>`, which does not implement the `Copy` trait
这是在循环的第一次迭代中转移向量的所有权,编译器告诉您后续迭代将违反 Rust 的所有权规则。
这里的解决方案是通过引用传递向量:
displayWord(&guessed_Letters);
..你的方法也应该接受一个引用:
fn displayWord(correctGuess: &Vec<char>) {
let mut currentWord = String::new();
for x in 0..5 {
currentWord.push(correctGuess[x]);
}
println!("Current guesses: {}", currentWord);
}
这可以缩短为使用切片并且仍然有效:
fn displayWord(correctGuess: &[char]) {
关于rust - 如何将向量解析为函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51956848/