如何访问数组类型的结构元素

时间:2015-07-07 23:16:40

标签: rust

我创建了以下结构

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;
    }
}

尝试编译时,我收到以下错误

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

让Buckets保留属性指纹更有意义吗?

1 个答案:

答案 0 :(得分:2)

类型Bucket是一个包含一个字段的元组结构,您可以使用.0访问该字段。

因此您可以将代码更改为:

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

您还需要将函数参数从&self更改为&mut self,以便您可以改变self的字段。