[英]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.而且我不明白我是如何为 Human 而不是为 Robot 结构得到这个错误的,也不知道如何在两者都实现 Guesser 特征的同时解决它......我尝试使用
Box<dyn Guesser>
但它也不起作用。
Actually I just tried something else, if you add Box<dyn Guesser>
you apparently need to instanciate it differently:实际上我只是尝试了别的东西,如果你添加
Box<dyn Guesser>
你显然需要以不同的方式实例化它:
let player: Box<dyn Guesser> = match player_type {
PlayerType::Human => Box::new(Human::new()),
PlayerType::Robot => Box::new(Robot::new())
};
This worked for me这对我有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.