How to create an array with a dimension that is generic? #1158
-
| Hello, pub struct CircularBuffer1D<S>
    where
        S: Clone + Zero,
{
    capacity: usize,
    head: usize,
    data: Array1<S>,
    total_num_samples_seen: usize,
}
impl<S> CircularBuffer1D<S>
    where
        S: Clone + Zero,
{
    pub fn new(capacity: usize) -> Self {
        CircularBuffer1D {
            capacity: capacity,
            head: 0,
            data: Array1::<S>::zeros(capacity),
            total_num_samples_seen: 0,
        }
    }
}I'm now trying to convert it into a generic on the dimension too. This is what I have so far: struct CircularBufferND<S, D>
    where
        S: Clone + Zero,
        D: Dimension + RemoveAxis
{
    capacity: usize,
    head: usize,
    data: Array<S, D>,
    total_num_samples_seen: usize,
}
impl<S, D> CircularBufferND<S, D>
    where
        S: Clone + Zero,
        D: Dimension + RemoveAxis
{
    fn new(capacity: usize, element_shape: Vec<usize>) -> Self {
        let mut final_shape_vec: Vec<Ix> = vec![capacity];
        final_shape_vec.extend(element_shape);
        CircularBufferND {
            capacity: capacity,
            head: 0,
            data: Array::<S, D>::zeros(final_shape_vec),
            total_num_samples_seen: 0,
        }
    }
}The compiler throws an error on the line  I tried building a Shape from the  | 
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
| The issue is that the  A good alternative is to create an empty shape using  impl<S, D> CircularBufferND<S, D>
    where
        S: Clone + Zero,
        D: Dimension + RemoveAxis
{
    fn new(capacity: usize, element_shape: Vec<usize>) -> Self {
        let ndim = 1 + element_shape.len();
        let mut final_shape: D = D::zeros(ndim);
        final_shape[0] = capacity;
        final_shape.as_array_view_mut().slice_mut(s![1..]).assign(&ArrayView::from(&element_shape));
        CircularBufferND {
            capacity: capacity,
            head: 0,
            data: Array::<S, D>::zeros(final_shape),
            total_num_samples_seen: 0,
        }
    }
}Note that this will panic if  | 
Beta Was this translation helpful? Give feedback.
The issue is that the
Array::zeros(shape)method requires the shape argument to be compatible with the dimension type, butVec<usize>as a shape is compatible only withIxDyn.A good alternative is to create an empty shape using
D::zeros(ndim), and then assign the axis lengths to the shape. Here's an example: