为什么不能在两个不同的映射函数中可变地借用变量?

如何解决为什么不能在两个不同的映射函数中可变地借用变量?

我在Rust中有一个迭代器,它在Vec<u8>上循环,并在两个不同的阶段应用相同的函数。我通过将几个map函数链接在一起来实现此目的。这是相关的代码(例如example_function_1example_function_2分别是替代变量和函数):

注意:example.chunks()是一个自定义函数!不是默认的切片!

let example = vec![0,1,2,3];
let mut hashers = Cycler::new([example_function_1,example_function_2].iter());

let ret: Vec<u8> = example
        //...
        .chunks(hashers.len())
        .map(|buf| hashers.call(buf))
        //...
        .map(|chunk| hashers.call(chunk))
        .collect();

这是Cycler的代码:

pub struct Cycler<I> {
    orig: I,iter: I,len: usize,}

impl<I> Cycler<I>
where
    I: Clone + Iterator,I::Item: Fn(Vec<u8>) -> Vec<u8>,{
    pub fn new(iter: I) -> Self {
        Self {
            orig: iter.clone(),len: iter.clone().count(),iter,}
    }

    pub fn len(&self) -> usize {
        self.len
    }

    pub fn reset(&mut self) {
        self.iter = self.orig.clone();
    }

    pub fn call(&mut self,buf: Bytes) -> Bytes {
        // It is safe to unwrap because it should indefinietly continue without stopping
        self.next().unwrap()(buf)
    }
}

impl<I> Iterator for Cycler<I>
where
    I: Clone + Iterator,{
    type Item = I::Item;

    fn next(&mut self) -> Option<I::Item> {
        match self.iter.next() {
            next => next,None => {
                self.reset();
                self.iter.next()
            }
        }
    }

    // No size_hint,try_fold,or fold methods
}

让我感到困惑的是,我第二次引用hashers时是这样说的:

error[E0499]: cannot borrow `hashers` as mutable more than once at a time
  --> libpressurize/src/password/password.rs:28:14
   |
21 |         .map(|buf| hashers.call(buf))
   |              ----- ------- first borrow occurs due to use of `hashers` in closure
   |              |
   |              first mutable borrow occurs here
...
28 |         .map(|chunk| hashers.call(chunk))
   |          --- ^^^^^^^ ------- second borrow occurs due to use of `hashers` in closure
   |          |   |
   |          |   second mutable borrow occurs here
   |          first borrow later used by call

这是行不通的,因为可变引用没有同时使用吗?

请让我知道是否需要更多信息/代码来回答这个问题。

解决方法

        .map(|buf| hashers.call(buf))

您可能会想,在上一行中,hashers是可变地借来调用的。没错(因为Cycler::call占用&mut self),但这不是编译器错误的所在。在这一行中,hashers是可变地借来的来构造闭包|buf| hashers.call(buf) ,并且借用的持续时间与闭包一样长。

因此,当您编写

        .map(|buf| hashers.call(buf))
        //...
        .map(|chunk| hashers.call(chunk))

您要构造两个同时存在的闭包(假设这是std::iter::Iterator::map),并为每个闭包可变地借入hashers,这是不允许的。

此错误实际上是在保护您免受副作用危害:在纯局部分析中,这两个{{{将执行1}},因为call()可以对闭包做任何他们想做的事情。给定您编写的代码,我认为您是故意这样做的,但是编译器不知道您知道自己在做什么。

(我们甚至不能仅仅因为它们是迭代器就预测到交错。在map()内可能有一个//...步骤,该步骤导致.filter()在每次调用hashers.call(buf)或其他会产生与输入数量不同的输出之间被多次调用。)

如果您知道“只要hashers.call(chunk)决定调用它的副作用之间的交错,那么您就可以通过map()或其他内部可变性来获得这种自由,例如dianhenglau's answer演示。

,

这是行不通的,因为可变引用没有同时使用吗?

不。 rules of references指出:“在任何给定时间,您都可以具有一个可变引用或任意数量的不可变引用”,无论它是否同时使用。有关规则背后的原因,请参见此answer

关于解决方法,由于您确定突变不会同时发生,因此可以按照this chapter中的说明使用std::cell::RefCell。将代码修改为:

use std::cell::RefCell;

let example = vec![0,1,2,3];
// Remove the "mut",wrap Cycler in RefCell.
let hashers = RefCell::new(Cycler::new([example_function_1,example_function_2].iter()));

let ret: Vec<u8> = example
    //...
    .chunks(hashers.borrow().len())
    // Borrow hashers as immutable inside the closure,then borrow the Cycler as mutable.
    .map(|buf| hashers.borrow_mut().call(buf))
    //...
    .map(|chunk| hashers.borrow_mut().call(chunk))
    .collect();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-