gpt4 book ai didi

rust - 可以在Rust中使用通用类型的特征对象吗?

转载 作者:行者123 更新时间:2023-12-03 11:47:09 24 4
gpt4 key购买 nike

我对如何使用Rust的trait对象感到困惑。我有很多模糊的部分理解,但最终我不明白我得到的错误。
我正在尝试在rust中实现命令模式,以便在终端上移动光标。我设置它来发送实现Command特征的特征对象,并通用键入Command特征。我不能使这个特性通用吗?
这是我的代码的示例版本:

pub trait Command<T> {
fn execute(&self, target_instance: &mut T);
}

pub trait Commandable<T> {
fn send(&mut self, cmd: Box<impl Command<T>>);
}
//-------------------------------------------------------

struct Cursor {
pos: (isize, isize),
}

impl Cursor {
fn move_me(&mut self, direction: (isize, isize)) {
self.pos.0 += direction.0;
self.pos.1 += direction.1;
}
}

impl Commandable<Cursor> for Cursor {
fn send(&mut self, cmd: Box<impl Command<Cursor>>) {
cmd.execute(self);
}
}

struct MoveCommand {
move_direction: (isize, isize),
}

impl MoveCommand {
pub fn new(move_direction: (isize, isize)) -> Self {
MoveCommand { move_direction }
}
}

impl Command<Cursor> for MoveCommand {
fn execute(&self, cursor: &mut Cursor) {
cursor.move_me(self.move_direction);
}
}
//------------------------------------------------------

fn handle_input(input: Option<&str>, target: &mut impl Commandable<Cursor>) {
let mut cmd: Option<Box<dyn Command<Cursor>>> = None;
if let Some(key) = input {
match key {
"K" => cmd = Some(Box::new(MoveCommand::new( (0, -1) ))),
"J" => cmd = Some(Box::new(MoveCommand::new( (0, 1) ))),
"H" => cmd = Some(Box::new(MoveCommand::new( (-1, 0) ))),
"L" => cmd = Some(Box::new(MoveCommand::new( (1, 0) ))),
_ => {}
}
}
if let Some(boxed_cmd) = cmd {
target.send(boxed_cmd); // <-----------------ERROR IS HERE
}
}

fn main() {
let mut cursor = Cursor { pos: (0, 0) };
handle_input(Some("K"), &mut cursor);
}
这是错误:
error[E0277]: the size for values of type `dyn Command<Cursor>` cannot be known at compilation time
--> src/main.rs:54:21
|
54 | target.send(boxed_cmd);
| ^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `dyn Command<Cursor>`

最佳答案

回答我自己的问题以帮助 future 的人们:
我的主要问题是我不了解dyn MyTraitObjimpl MyTraitObj之间的区别。我可以互换使用它们,所以一旦将所有impl交换为dyn,我发布的代码就会被编译。
@LeoVen对此进行了链接,这为我解决了困惑:What is the difference between trait and impl trait when used as method arguments?
感谢所有提供帮助的人。

关于rust - 可以在Rust中使用通用类型的特征对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65314766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com