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?
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With