[Solved] Container of arbitary type with implementation for general type

Hello! I want to build a container that can store arbitrary type and do a few operations on it (that is for the general type). It would look something like:

struct TripletBuffer<T> {
    data: [T; 3],
}

impl TripletBuffer<T> {
    fn insert(&mut self, data: T) {
        let [a, b, c] = self.data;
        self.data = [data, b, c];
    }
}

How could I implement something like this?

(This example does not compile)

Silly me forgot to show Rust the type parameter before:

impl<T> TripletBuffer<T> {
    fn insert(&mut self, data: T) {
        let [a, b, c] = self.data;
        self.data = [data, b, c];
    }
}


What's wrong with your implementation?

cannot find type T in this scope
not found in this scope

Once you've fixed the impl<T> issue, the problem with your code is that you are trying to take (move) the value out of self.data, but since you only have a mutable reference to self you can't do this without replacing it with another value. Maybe you want this instead?

    self.data[0] = data;
3 Likes

Thank you!

Should be

impl<T> TripletBuffer<T> {

Giving the actual error message would have been even better.

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.