[英]error[E0308]: mismatched types - expected struct `Test`, found `&Test`
[英]error[E0308]: mismatched types — expected `&str`, found struct `std::string::String`
我正在制作井字游戲。 代碼不完整,但我被困在這里。 我想將array_display
打印到控制台,但是當我分配字符串時,會彈出一個錯誤。
use std::io;
fn main() {
let mut player1: String = String::new();
let mut player2: String = String::new();
let mut positions = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
let mut lets_play = true;
println!("Welcome to tic tac toe");
println!("Player 1 please select what symbol you want to be : (x or o)");
io::stdin().read_line(&mut player1);
player1 = player1.to_lowercase();
println!("{:?}", player1);
if player1.trim() == "x" {
player1 = String::from("x");
player2 = String::from("o");
println!("Player 1 is x");
} else if player1.trim() == "o" {
player1 = String::from("o");
player2 = String::from("x");
println!("Player 1 is o");
} else {
println!("Input is not valid");
lets_play = false;
}
if lets_play {
println!("Let's start the game :");
print_board(&mut positions);
} else {
println!("Please reset the game");
}
}
fn print_board(arr: &mut [&str]) {
let mut counter = 0;
let mut array_display = ["1", "2", "3"];
let mut array_position = 0;
let mut string_for_array = String::new();
for i in 0..arr.len() {
string_for_array.push_str(arr[i]);
counter += 1;
if counter == 3 {
println!(
"array_display[{}] value = {}",
array_position, string_for_array
);
array_display[array_position] = string_for_array.to_string();
println!("String to push {:?}", string_for_array);
string_for_array = String::from("");
println!("Array position {}", array_position);
array_position += 1;
counter = 0;
}
}
}
錯誤:
error[E0308]: mismatched types
--> src/main.rs:52:45
|
52 | array_display[array_position] = string_for_array.to_string();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| expected `&str`, found struct `std::string::String`
| help: consider borrowing here: `&string_for_array.to_string()`
您代碼中的當前問題是string_for_array.to_string()
創建了一個新的String
,但array_display
數組包含&str
引用。
編譯器在此處給出的建議(替換為&string_for_array.to_string()
)不起作用,因為.to_string()
的結果將.to_string()
釋放,您將獲得無效的&str
引用。
所以,問題是:某些變量需要擁有該字符串。 由於string_for_array
是后來修改的,所以不能使用。 自然的選擇是array_display
(因為無論如何該字符串都將存在於此)。 因此,首先修改這個數組以包含擁有的String
而不是&str
引用:
let mut array_display = ["1".to_owned(), "2".to_owned(), "3".to_owned()];
然后其余的代碼將被編譯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.