【问题标题】:Rust's Enums vs Generics [closed]Rust 的枚举与泛型 [关闭]
【发布时间】:2020-07-17 05:25:43
【问题描述】:

在 Rust 中似乎有两种类似的数据结构方式:

pub enum FooEnum {
    Bar {ts: DateTime, bar: Bar},
    Baz {ts: DateTime, baz: Baz}
}

pub struct FooGeneric<T: BarAndBazLike> {
    pub ts: DateTime<Utc>,
    pub content: T
}

我可以看到枚举方法为我提供了更好的字段名foobar,代价是重复定义ts

使用通用方法有什么好处吗? (我将使用带有 JSON 和 bincode 的 serde。)

【问题讨论】:

  • 枚举的所有变体都将具有相同的大小,而通用结构(可能)不会。 IE。您将无法将具有不同泛型参数的结构实例分配给同一个变量,而您将能够将不同的枚举变体分配给同一个枚举变量。不 - 枚举不是运行时多态的 - 如果您需要运行时多态,请阅读 traits 和动态调度
  • 这能回答你的问题吗? Why does Rust have struct and enum?

标签: generics enums rust


【解决方案1】:

泛型通常具有更好的性能,因为编译器可以为每个变体生成专门的代码。它们占用的内存也略少,因为枚举需要存储判别式来跟踪当前正在使用的变体。

OTOH,枚举不需要在编译时知道类型,甚至可以在执行期间动态更改内容类型。

如果您不想重复 ts 字段,另一种选择是使用 either

extern crate either; // 1.5.3
extern crate chrono; // 0.4.13

use either::Either;
use chrono::{ DateTime, Utc };

pub struct Bar {}
pub struct Baz {}

pub struct Foo {
    pub ts: DateTime<Utc>,
    pub content: Either<Bar, Baz>,
}

或者为 content 字段使用自定义枚举:

extern crate chrono; // 0.4.13

use chrono::{ DateTime, Utc };

pub struct Bar {}
pub struct Baz {}

pub enum BarOrBaz {
    Bar (Bar),
    Baz (Baz),
}

pub struct Foo {
    pub ts: DateTime<Utc>,
    pub content: BarOrBaz,
}

【讨论】:

    猜你喜欢
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多