【问题标题】:mismatched types expected trait object `dyn Trait` found struct `Struct`不匹配的类型预期特征对象`dyn Trait`找到结构`Struct`
【发布时间】:2022-11-20 21:59:58
【问题描述】:

我有那些结构和特征:

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

我想根据用户输入存储其中之一,但我得到:

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

而且我不明白我是如何为人类而不是机器人结构得到这个错误的,也不知道如何在两者都实现 Guesser 特征的同时解决它...... 我尝试使用Box&lt;dyn Guesser&gt;,但它也不起作用。

【问题讨论】:

  • 你应该使用Box&lt;dyn Guesser&gt;。怎么没效果?

标签: rust struct


【解决方案1】:

实际上我只是尝试了别的东西,如果你添加 Box&lt;dyn Guesser&gt; 你显然需要以不同的方式实例化它:

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

这对我有用

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 2019-12-22
    相关资源
    最近更新 更多