没有继承的不同事物列表?

时间:2017-07-03 15:49:20

标签: rust

我知道如何使用像Java这样的继承语言或像JavaScript这样的无类型语言来制作相关内容的列表,但我无法弄清楚如何在Rust中执行此操作。这将产生错误,因为Dereference中的数组大小在编译时是未知的。

#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct Appearance<'a> {
    identity:   &'a u64, 
    role:       &'a str
}

struct Dereference<'a> {
    set:        [&'a Appearance<'a>]
}

fn main() {
    let r = "hair_color";
    let i1 = 42;
    let i2 = 43;
    let a1 = Appearance{identity: &i1, role: r};
    let a2 = Appearance{identity: &i2, role: r};
    let d1 = Dereference{set: [&a1]};
    let d2 = Dereference{set: [&a1, &a2]};
    let list: Vec<Dereference> = vec!(d1, d2);
}

但是,set中的Dereference成员将是一个小规模的数组。让我们说小于32,最常见的是1或2,很少3,几乎不大于此。我可以创建32个结构和32个列表,但为了方便起见,我真的想以更聪明的方式做到这一点。即使我必须创建32个结构,至少有一个列表可以提供很多帮助。我需要它同时具有内存和性能效率。我如何在Rust中实现这一目标?

2 个答案:

答案 0 :(得分:6)

这与继承无关;类型[&'a Appearance<'a>]是未分类的类型。它只能在指针后面引用,如&[&'a Appearance<'a>]

您可能想要的是Vec<&'a Appearance<'a>>。实际上Vec<Appearance>可能会更好,而#[derive(Copy)]上的Appearance可能更好,因为Appearance本身就是一堆引用,并且引用一堆引用并没什么意义。

虽然你的例子没有尝试列出相关的东西,(它只是列出了Appearance s),但在Rust中有两种方法可以做到这一点。一种是使用枚举,即你执行类似enum Things {Thing1(Type1), Thing2(Type2), ...}的操作,并存储Vec<Things>。这避免了额外的分配,但是更多的打字。或者,您可以使用特征对象,通过定义具有所需方法的特征,针对相关类型实施特征,以及使用Vec<&TraitName>Vec<Box<TraitName>>

答案 1 :(得分:0)

Rust中的数组仅在您在编译时知道其大小时才有用,例如:

struct 3DPoint {
    position: [f32; 3],
    // etc.
}

如果在编译时不知道大小,请使用名为Vec的动态数组:

#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct Appearance<'a> {
    identity:   &'a u64, 
    role:       &'a str
}

struct Dereference<'a> {
    set:        Vec<&'a Appearance<'a>>
}

fn main() {
    let r = "hair_color";
    let i1 = 42;
    let i2 = 43;
    let a1 = Appearance{identity: &i1, role: r};
    let a2 = Appearance{identity: &i2, role: r};
    let d1 = Dereference{set: [&a1]};
    let d2 = Dereference{set: [&a1, &a2]};
    let list: Vec<Dereference> = vec!(d1, d2);
}

当你在Rust中开发时,总是要考虑堆栈。如果我理解你的问题,你想要在不指定大小的情况下堆积东西:这是不可能的。