#What's the idiomatic way to distinguish between stack and heap allocation in a data structure?

5 messages · Page 1 of 1 (latest)

opaque kiln
#

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])
    };
}```
sand bobcat
#

you might want to look at how ndarray does things — I haven't myself but I believe it is basically what you are building

unreal wind
#

What I'd say is that you don't actually care about stack vs heap, what you care about is dynamic vs const.

#

After all, I can make a Box<GridStack<i32, 100>> which puts a "grid stack" on the heap.