rust - How to access a elements of a struct of type array -
i created 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 { in 0..bucket_size { //here error if (self[i usize] == 0) { self[i usize] = fp; return true; } } return false; } }
when trying compile following error
error: cannot index value of type `&bucket::bucket`
does make more sense make buckets hold property fingerprints instead?
the type bucket
tuple struct 1 field, can access .0
.
so can change code to:
if (self.0[i usize] == 0) { self.0[i usize] = fp; return true; }
you need change function argument &self
&mut self
can mutate fields of self
.
Comments
Post a Comment