小编Adm*_*VII的帖子

如何确保Rust向量仅包含交替类型?

我有一组在A和B之间交替的数据。这些都是有效的选择:

  • A -> B -> A
  • A -> B -> A -> B
  • B -> A -> B
  • B -> A -> B -> A

我想利用类型系统来确保交替属性在编译时被检查,同时保持良好的性能。

解决方案1:链表

struct A {
    // data
    next: Option<B>,
}

struct B {
    // data
    next: Option<Box<A>>,
}
Run Code Online (Sandbox Code Playgroud)

问题在于此数据结构的性能充其量是最差的。链接列表频繁发生高速缓存未命中,并且对于迭代数据结构而言,这是非常糟糕的。

解决方案2:Vec +枚举

enum Types {
    A(DataA),
    B(DataB),
}

type Data = Vec<Types>;
Run Code Online (Sandbox Code Playgroud)

使用此解决方案,缓存局部性要好得多,因此可以提高性能。但是,这并不能阻止2 As并排放置。还有一个事实是,每次迭代都需要检查类型,而由于非正式的定义,因此不需要。

解决方案3:组合

struct A {
    // data, default in first link = empty
    b: Option<B>,
}

struct B {
    // data
} …
Run Code Online (Sandbox Code Playgroud)

types rust data-structures

8
推荐指数
1
解决办法
174
查看次数

跳过超类__init__的一部分?

我有一个班级又一个班级。我想跳过初始化过程的一部分,例如:

class Parent:
    __init__(self, a, b, c, ...):
        # part I want to keep:
        self.a = a
        self.b = b
        self.c = c
        ...
        # part I want to skip, which is memory and time consuming
        # but unnecessary for the subclass:
        self.Q = AnotherClass()

class Child(Parent):
    __init__(self):
        #a part of the parent initialization process, then other stuff
Run Code Online (Sandbox Code Playgroud)

我提出的两个解决方案是:

  • 将一个抽象类作为该类的父Parent类,该类不包含Child,或初始化的不需要部分
  • 仅复制我要在子级中进行的父级初始化的部分

哪个最好,或者有更好的方法?

python inheritance

1
推荐指数
1
解决办法
392
查看次数

标签 统计

data-structures ×1

inheritance ×1

python ×1

rust ×1

types ×1