我正在用 Rust 制作游戏,需要制作一个 UiElements
向量来循环并处理输入或绘图。
所以我创建了一个 UiElement
特征,将其传递到一个向量中,并表示我的特征不是对象安全的。
我尝试将dyn UiElement
放入一个盒子中,但仍然不起作用。我还将特征方法的返回类型替换为 i32(也许只是字符串和向量存在特征错误),即使这不起作用
我还读过https://doc.rust-lang.org/reference/items/traits.html#object-safety检查我的特质是否遵循所有规则
这是代码
元素.rs
#[derive(Debug, Clone, PartialEq)]
pub enum Rect {
Color(ColorRect),
Image(ImageRect)
}
pub trait UiElement: Debug + Clone {
fn get_id(&self) -> String;
fn get_rects(&self) -> Vec<Rect>;
}
游戏.rs
#[derive(Debug, Clone)]
pub struct Game {
ui_elements: Vec<Box<dyn UiElement>>, //problem here
color_rects: Vec<ColorRect>,
image_rects: Vec<ImageRect>
}
最佳答案
按照 comment 中的建议删除了克隆
:
It's not object safe because it has Clone as a supertrait, and Clone isn't object safe.
trait.rs
pub trait UiElement: Debug {
fn get_id(&self) -> String;
fn get_rects(&self) -> Vec<Rect>;
}
关于rust - 为什么这个特性不是对象安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74178811/