Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a elements of a struct of type array

Tags:

rust

I created the following struct

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 trying to compile it i get the following error

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

Does it make more sense to make Buckets hold a property fingerprints instead?

like image 874
Seif Lotfy Avatar asked Jul 07 '15 23:07

Seif Lotfy


People also ask

How do you access the elements of a struct array?

1. Array elements are accessed using the Subscript variable, Similarly Structure members are accessed using dot [.] operator. Structure written inside another structure is called as nesting of two structures.

How do you access data from a struct?

Structures store data in containers called fields, which you can then access by the names you specify. Use dot notation to create, assign, and access data in structure fields. If the value stored in a field is an array, then you can use array indexing to access elements of the array.

How do you access a field of struct in Matlab?

Access Field of Scalar StructureWhen you use the getfield function, you can access a field of the structure returned by a function without using a temporary variable to hold that structure. You also can access a field using dot notation.


1 Answers

The type Bucket is a tuple struct with one field, which 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 of self.

like image 143
mbrubeck Avatar answered Oct 23 '22 09:10

mbrubeck