无法从实现中修改结构字段:“不能将不可变的借用内容作为可变借用"; [英] Cannot modify a struct field from implementation: "cannot borrow immutable borrowed content as mutable"

查看:36
本文介绍了无法从实现中修改结构字段:“不能将不可变的借用内容作为可变借用";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个可产生素数的迭代器.我将已经找到的素数存储在 Vec 中.

I'm trying to implement an iterator which will yield prime numbers. I store already found prime numbers in a Vec<u64>.

这是我的实现:

struct Primes {
    primes: Vec<u64>,
}

impl Primes {
    fn new() -> Primes {
        Primes { primes: vec!(2, 3) }
    }

    fn iter(&self) -> PrimesIterator {
        PrimesIterator { primes: &self.primes, index : 0 }
    }
}

struct PrimesIterator<'a> {
    primes: & 'a Vec<u64>,
    index: usize,
}

impl<'a> Iterator for PrimesIterator<'a> {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        if self.index < self.primes.len() {
            let result = self.primes[self.index];
            self.index += 1;
            Some(result)
        } else {
            let mut n = *self.primes.last().unwrap();
            loop {
                n += 2;
                if is_prime(self.primes, n) {
                    self.primes.push(n);
                    self.index += 1;
                    return Some(n);
                }
            }
        }
    }
}

fn is_prime(primes: &[u64], n: u64) -> bool {
    for &p in primes.iter() {
        if n % p == 0 {
            return false;
        }
        if p * p > n {
            return true;
        }
    }
    return false;
}

但是当我尝试编译它时,出现以下错误:

but when I'm trying to compile it, I'm getting the following error:

main.rs: error: cannot borrow immutable borrowed content `*self.primes` as mutable
main.rs:                     self.primes.push(n);

我将 self 声明为 &mut 所以我真的不明白这里出了什么问题以及如何解决这个问题.

I declared self as &mut so I don't really understand what's wrong here and how to fix that.

推荐答案

您的 PrimesIterator 类型包含对 Vec 的非可变引用.您需要将其声明为可变引用:

Your PrimesIterator type contains a non-mutable reference to a Vec<u64>. You need to declare it as a mutable reference:

struct PrimesIterator<'a> {
    primes: &'a mut Vec<u64>,
    index: usize,
}

这当然需要您还修改 iter() 函数以确保它传递可变引用:

This will of course require you to also modify the iter() function to make sure it passes a mutable reference:

impl Primes {
    fn new() -> Primes {
        Primes { primes: vec!(2, 3) }
    }

    fn iter(&mut self) -> PrimesIterator {
        PrimesIterator { primes: &mut self.primes, index : 0 }
    }
}

这篇关于无法从实现中修改结构字段:“不能将不可变的借用内容作为可变借用";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆