简体   繁体   中英

mismatched types expected trait object `dyn Trait` found struct `Struct`

I have those structs and trait:

use std::io;

pub struct Human {}

impl Human {
    pub fn new () -> Self {
        Self {}
    }
}
pub struct Robot {
    previous_guess: u32
}

impl Robot {
    pub fn new () -> Self {
        Self {
            previous_guess: 0
        }
    }
}

pub trait Guesser {
    fn guess(&mut self) -> String;
}

impl Guesser for Human {
    fn guess(&mut self) -> String {
        let mut curr_guess = String::new();
        io::stdin()
            .read_line(&mut curr_guess)
            .expect("Failed to read line");
        curr_guess
    }
}

impl Guesser for Robot {
    fn guess(&mut self) -> String {
        self.previous_guess = self.previous_guess + 1;
        self.previous_guess.to_string()
    }
}

and I want to store one of them according to the user input but I get:

fn main() {
    let player_type = get_player_type().unwrap();

// ERROR - mismatched types expected trait object `dyn Guesser` found struct `Human`
    let player: dyn Guesser = match player_type {
        PlayerType::Human => Human::new(),
        PlayerType::Robot => Robot::new()
    };
}


fn get_player_type() -> Result<PlayerType, String> {
    let mut is_human = String::new();
    println!("Who would you like to see playing ? (me / robot):");
    io::stdin()
        .read_line(&mut is_human)
        .expect("Failed to read line");

    match is_human.trim().to_lowercase().as_ref() {
        "me" => { Ok(PlayerType::Human) },
        "robot" => { Ok(PlayerType::Robot) },
        _ => { Err("Please type 'me' or 'robot'".to_string()) }
    }
}

and I don't understand how I get this error for the Human but not for the Robot struct neither how to solve it while both implement the Guesser trait... I tried using Box<dyn Guesser> but it doesn't work either.

Actually I just tried something else, if you add Box<dyn Guesser> you apparently need to instanciate it differently:

    let player: Box<dyn Guesser> = match player_type {
        PlayerType::Human => Box::new(Human::new()),
        PlayerType::Robot => Box::new(Robot::new())
    };

This worked for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM