How to access elements of a type array structure

I created the following structure

pub const BUCKET_SIZE: usize = 4;

pub const FINGERPRINT_SIZE: usize = 1;

pub struct Fingerprint ([u8; FINGERPRINT_SIZE]);

impl Fingerprint {
    pub fn new(bytes: [u8; FINGERPRINT_SIZE]) -> Fingerprint {
        return Fingerprint(bytes);
    }
}

pub struct Bucket ([Fingerprint; BUCKET_SIZE]);

impl Bucket {
    pub fn new(fingerprints: [Fingerprint; BUCKET_SIZE]) -> Bucket {
        Bucket(fingerprints)
    }
    pub fn insert(&self, fp: Fingerprint) -> bool {
        for i in 0..BUCKET_SIZE {



            //HERE IS THE ERROR
            if (self[i as usize] == 0) {
                self[i as usize] = fp;
                return true;
            }



        }
        return false;
    }
}

      

When I try to compile it, I get the following error:

error: cannot index a value of type `&bucket::Bucket`

      

Does it make sense to make Buckets store property prints instead?

+3


source to share


1 answer


Type Bucket

is a root structure with one field that you can access with .0

.

So, you can change the code to:



        if (self.0[i as usize] == 0) {
            self.0[i as usize] = fp;
            return true;
        }

      

You will also need to change the function argument from &self

to &mut self

so that you can mutate the fields self

.

+2


source







All Articles