Hi! I am currently trying to have an easy way to access a nested Vec. In the past I wrote it similar to v1.get(0).map(|v2| v2.get(0)).flatten(). Which works, but is always a bit long to write. I'd prefer something like v1.dig(0, 0). So i started to fiddle around and came up with the following solution:
While implementing I started to copy a Generic function for Vec<Vec<Vec<T>>> from Vec<Vec<T>>>. I've seen it in an open source repository before, but was curious if this is considered best practise. So my questions are:
Is there an easier way access nested Vectors?
Would there be an easier way to implement something like Ruby's Array#dig method, without copying the method? Or is this the perfect case for a marco?
Nitpick: .map().flatten() is better expressed as and_then():
v1.get(0).and_then(|v2| v2.get(0))
The thing I would suggest, in matters of best practice, is: you usually shouldn't have just nested vectors.
If your application is a “matrix” or “multidimensional array”, then Vec<Vec<T>> is an inefficient and inconvenient data structure, and you should use a library like ndarray.
If you’re using serde or similar, and deserializing data which is represented on disk as nested lists, then you should deserialize it into a more specific data type, which can have methods to provide the specific best kind of access.
More broadly, if you find yourself using dig a lot, there is probably a less-generic function, or a wrapper data type, you can write which will make your code better.
It’s possible that in fact dig is the best fit for your use case, since you haven’t described it. I only say that my design intuition is suspicious that there is a better solution.