I'm trying to make a data structure that can live either on the stack or the heap and I'm wondering whether it's most idiomatic to use a type parameter or a trait to bridge the commonalities between the different allocation types. Or maybe there's some secret third method I am not thinking of?
Type parameter:
struct GridGeneric<T> {
dimensions: (usize, usize),
contents: T
}
pub fn main() {
let grid_stack = GridGeneric {
dimensions: (2, 3),
contents: [1, 2, 3, 4, 5, 6]
};
let grid_heap = GridGeneric {
dimensions: (2, 3),
contents: Box::new([1, 2, 3, 4, 5, 6])
};
}```
Trait:
```rust
trait Grid {
/* ... */
}
struct GridStack<T, const N: usize> {
dimensions: (usize, usize),
contents: [T; N]
}
struct GridHeap<T> {
dimensions: (usize, usize),
contents: Box<[T]>
}
impl<T, const N: usize> Grid for GridStack<T, N> {
/* ... */
}
impl<T> Grid for GridHeap<T> {
/* ... */
}
pub fn main() {
let grid_stack = GridStack {
dimensions: (2, 3),
contents: [1, 2, 3, 4, 5, 6]
};
let grid_heap = GridHeap {
dimensions: (2, 3),
contents: Box::new([1, 2, 3, 4, 5, 6])
};
}```