comptime vs runtime
That is the main issue I see here, you need to decide between either handling the shape at comptime which would allow you to use different types depending on the shape picked at comptime, or handle it all at run time which means you need to pick a type that can handle all shapes.
I think one way you could do this is by renaming/repurposing toArray
to toShape
and adding a comptime shape
parameter to it, which then is used to calculate the return type, within the body of the function you check at run time that the runtime shape matches the comptime shape, if it doesn’t you either error or panic.
Another problem is the whole issue of multidimensional slices (slices need their own storage and point to other storage combined with creating new data, you end up needing dynamic memory allocation), if you are going this route where the shape has to be provided as a comptime parameter, then there isn’t a good reason to use slices at all, because if the shape is known at comptime you can instead use multidimmensional arrays like in this answer:
If you don’t want to provide the shape as a comptime parameter, you could instead return a tagged union that enumerates the possible variants (effectively just delaying the choice by wrapping it in a type that can represent every choice), but if you want to support a wide combination of possible shapes that might end up too messy and difficult. Also in the end the union would mostly serve as a way to indicate at run time which of the shapes was chosen and then the person receiving the value would have to switch on the tagged union, selecting one of its variants (and at that point that code branch would again know the shape at comptime (because that branch only gets chosen for that variant)).
Overall I think it would be helpful if you described your overall goals and constraints, so that we can make more specific suggestions how you could reach your goal.
For example whether you really want to process all kinds of generic shapes, or more specific ones, whether you know which shapes will ever be needed at comptime, or your program only finds that out at run time.
How you need to access the data, what operations you need on the data, etc.
It is easier to deal with (and write efficient code for) specific comptime known shapes then having to deal with all possible shapes at run time.
You also might be interested in these projects:
I don’t understand the details of those projects well enough, but from what I have gathered they also deal with lots of different dimmensional data, so there may be something there that is related to what you are trying to do.