简体   繁体   English

错误 [E0308]: 不匹配的类型 — 预期为 `&str`,找到结构体 `std::string::String`

[英]error[E0308]: mismatched types — expected `&str`, found struct `std::string::String`

I am making a tic-tac-toe game.我正在制作井字游戏。 The code is not complete, but I am stuck here.代码不完整,但我被困在这里。 I want to print array_display to the console, but when I assign the string, an error pops-up.我想将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:错误:

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()`

The current issue in your code is that string_for_array.to_string() creates a new String , but the array_display array contains &str references.您代码中的当前问题是string_for_array.to_string()创建了一个新的String ,但array_display数组包含&str引用。

The suggestion the compiler gives here (replacing with &string_for_array.to_string() ) does not work, because the result of .to_string() will be freed at the end of the line and you would have an invalid &str reference.编译器在此处给出的建议(替换为&string_for_array.to_string() )不起作用,因为.to_string()的结果将.to_string()释放,您将获得无效的&str引用。

So, the issue is: some variable needs to own that string.所以,问题是:某些变量需要拥有该字符串。 Since string_for_array is modified later, it can't be used.由于string_for_array是后来修改的,所以不能使用。 The natural choice is array_display (because that's where that string will live anyway).自然的选择是array_display (因为无论如何该字符串都将存在于此)。 So, first modify this array to contain owned String s instead of &str references:因此,首先修改这个数组以包含拥有的String而不是&str引用:

    let mut array_display = ["1".to_owned(), "2".to_owned(), "3".to_owned()];

And then the rest of the code will compile.然后其余的代码将被编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误[E0308]:类型不匹配 - 预期结构 `Test`,发现 `&Test` - error[E0308]: mismatched types - expected struct `Test`, found `&Test` 错误[E0308]:预期类型不匹配 `()`,发现 `bool`。 如何消除此错误? - error[E0308]: mismatched types expected `()`, found `bool`. How to remove this error? 错误[E0308]:类型不匹配,默认泛型类型无效 - error[E0308]: mismatched types , Default generic type is invalid 为什么我可以添加一个字符串和一个引用,而不是两个字符串? (E0308:类型不匹配) - Why can I add a String and a reference, but not two Strings? (E0308: Mismatched types) 字符串变量赋值期间的 E0308 - E0308 during String variable assignment 类型不匹配:在分配字符串时预期&str找到了字符串 - Mismatched types: expected &str found String when assigning string 预期的struct`std :: string :: String`,找到了struct`std :: str :: Split` - expected struct `std::string::String`, found struct `std::str::Split` std :: fs ::文件+文档+试试! = E0308 - std::fs::File + documentation + try! = E0308 反序列化 reqwest 查询错误 rustc(E0308) - Deserialize reqwest query error rustc(E0308) 为什么`name = * name.trim();`给我`预期的结构`std :: string :: String`,找到str`? - Why does `name = *name.trim();` give me `expected struct `std::string::String`, found str`?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM