Should I use enums or boxed trait objects to emulate polymorphism?

后端 未结 2 812
忘掉有多难
忘掉有多难 2020-12-17 21:31

Using the enum Axes to confine Coordinate and Quaternion:

#[derive(Clone)]
pub enum Axes {
    Coordinate {
        x:          


        
2条回答
  •  旧巷少年郎
    2020-12-17 21:50

    Another difference not mentioned in @Kwarrtz's answer is memory related.

    • enums can be stored directly on the stack, while a boxed trait will always require the heap. That is, enums are cheap to create, but boxed traits are not.
    • an enum instance will always be as big as its biggest variant (plus a discriminant in most cases), even if you store mostly small variants. This would be a problem in a case like this:

      enum Foo {
          SmallVariant(bool),
          BigVariant([u64; 100]),
      }
      

      If you were to store N instances of this type in an vector, the vector would always need N*(100*sizeof:: + sizeOfDiscriminant) bytes of memory, even when the vector only contains SmallVariants.

      If you were using a boxed trait, the vector would use N * sizeOfFatPointer == N * 2 * sizeof::.

提交回复
热议问题