Store dynamic lists of the same length without redundancy

I need to store (and access and mutate) a lot of n-dimension points of type T: Sized, where n is dynamic (so I cannot use arrays, tuples, structs).

Since all the points have the same dimension, I don't need to store the length of each point, so I would prefer to avoid everything that contains the length (Vec, slice, pointer). I think the ideal would be a reference without size.

If it's possible, what is the best way?

How about

struct PointList<T> {
    list: Vec<T>,
    point_len: usize,
}

Then when you look up, multiply with point_size and return a slice.

1 Like

You are basically looking for a matrix. A row or column then represents a point.
There are a number of crates that can handle this, ndarray is one of them.

1 Like

This works:

struct Space<T> {
    points: Vec<T>,
    dimensions: usize,
}

impl<T: Clone> Space<T> {
    fn get(&self, ind: usize) -> &[T] {
        let offset = ind*self.dimensions;
        &self.points[offset..offset+self.dimensions]
    }
    
    fn set(&mut self, ind: usize, val: &[T]) {
        let offset = ind*self.dimensions;
        self.points[offset..offset+self.dimensions].clone_from_slice(val);
    }
}

This is simpler than what I've tried (without success) with raw pointers indeed...

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.