解决嵌套可变借用conflct的惯用方法

时间:2017-06-27 08:43:31

标签: rust borrow-checker

考虑下面的最小示例,它提供了我在一些实际代码中遇到的情况:

error[E0500]: closure requires unique access to `hs0` but `*hs0` is already borrowed
 --> <anon>:9:21
  |
9 |     hs0.get("").map(|x| fn1(x, hs0, hs1));
  |     ---             ^^^        ---      - borrow ends here
  |     |               |          |
  |     |               |          borrow occurs due to use of `hs0` in closure
  |     |               closure construction occurs here
  |     borrow occurs here

借阅检查员不满意:

fn0

on the Rust playground

我理解上面的错误消息,我想知道解决此问题的惯用方法。请注意:

  • 出于可读性/可测试性原因,我希望fn1fn1成为单独的函数。 (即他们自己独自理解。)

  • 我想在fn0链式通话中使用相同的参数从.map(...)拨打.map

唯一明智的选择是不使用import itertools import os with open(os.path.join(os.getcwd(),'keywords.txt'), 'r') as keyfile: keywords_list = keyfile.readlines() keywords_perm = [] new_file = [] with open(os.path.join(os.getcwd(),'sentences.txt'), 'r') as sentences: sentences_list = sentences.readlines() with open(os.path.join(os.getcwd(),'multiple-sentances.txt'), 'w') as new: i = 0 for key in keywords_list: perm = itertools.permutations(key.split()) for element in perm: keywords_perm.append(element) if sentences_list[i].find(" ".join(key.split())) != -1: new.write(sentences_list[i][:sentences_list[i].find(" ".join(key.split()))] + " ".join(key.split()) + "\n") else: i += 1 new.write(sentences_list[i][:sentences_list[i].find(" ".join(key.split()))] + " ".join(key.split()) + "\n") with open(os.path.join(os.getcwd(),'permutated-keywords.txt'), 'w') as out: for i in range (0, len(keywords_perm)): out.write(" ".join(keywords_perm[i]) + "\n") 吗?

1 个答案:

答案 0 :(得分:5)

粗略地说,hs0仍然借用,直到没有任何参考。也就是说,虽然x: &String存在,但您不能随意借用hs0。这意味着我们需要做一些事情来结束x的生命周期,比如将其转换为String并将该字符串传递给下一个map

fn fn0(hs0: &mut HS, hs1: &mut HS) {
    hs0.get("").map(|x| x.clone()).map(|x| fn1(x, hs0, hs1));
}