- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个持续的编译错误,其中 Rust 提示我在尝试可变借用时有一个不可变借用,但不可变借用来自另一个范围,我没有从中带来任何东西。
我有一些代码可以检查 map 中的值,如果它存在,则返回它,否则它需要以各种方式改变 map 。问题是我似乎无法找到一种方法让 Rust 让我同时做这两个操作,即使这两个操作是完全分开的。
这是一些无意义的代码,它们遵循与我的代码相同的结构并显示出问题:
use std::collections::BTreeMap;
fn do_stuff(map: &mut BTreeMap<i32, i32>, key: i32) -> Option<&i32> {
// extra scope in vain attempt to contain the borrow
{
// borrow immutably
if let Some(key) = map.get(&key) {
return Some(key);
}
}
// now I'm DONE with the immutable borrow, but rustc still thinks it's borrowed
map.insert(0, 0); // borrow mutably, which errors
None
}
error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable
--> src/lib.rs:14:5
|
3 | fn do_stuff(map: &mut BTreeMap<i32, i32>, key: i32) -> Option<&i32> {
| - let's call the lifetime of this reference `'1`
...
7 | if let Some(key) = map.get(&key) {
| --- immutable borrow occurs here
8 | return Some(key);
| --------- returning this value requires that `*map` is borrowed for `'1`
...
14 | map.insert(0, 0); // borrow mutably, which errors
| ^^^^^^^^^^^^^^^^ mutable borrow occurs here
match
通过
return
退出函数,而另一个什么都不做并离开范围。
return
转义范围语句,但它阻止了函数中更远的借用是荒谬的——程序不可能返回并继续运行!如果我在那里返回其他东西,错误就会消失,所以我认为这就是借用检查器被挂断的原因。这对我来说就像一个错误。
最佳答案
这是一个 known issue这将通过 non-lexical lifetimes 的 future 迭代来解决,但是是 当前未处理 从 Rust 1.51 开始。
如果您要插入与查找相同的 key ,我建议您使用 use the entry API反而。
您现在可以添加一些低效率来解决此问题。如果效率低下是 Not Acceptable ,there are deeper workarounds .HashMap
一般的想法是添加一个 bool 值,告诉您一个值是否存在。这个 bool 值不卡在引用上,所以没有借用:
use std::collections::BTreeMap;
fn do_stuff(map: &mut BTreeMap<i32, i32>, key: i32) -> Option<&i32> {
if map.contains_key(&key) {
return map.get(&key);
}
map.insert(0, 0);
None
}
fn main() {
let mut map = BTreeMap::new();
do_stuff(&mut map, 42);
println!("{:?}", map)
}
Vec
类似的情况可以通过使用元素的索引而不是引用来解决。与上面的情况一样,由于需要再次检查切片边界,这可能会导致效率低下。
fn find_or_create_five<'a>(container: &'a mut Vec<u8>) -> &'a mut u8 {
match container.iter_mut().find(|e| **e == 5) {
Some(element) => element,
None => {
container.push(5);
container.last_mut().unwrap()
}
}
}
你可以写:
fn find_or_create_five<'a>(container: &'a mut Vec<u8>) -> &'a mut u8 {
let idx = container.iter().position(|&e| e == 5).unwrap_or_else(|| {
container.push(5);
container.len() - 1
});
&mut container[idx]
}
非词法生命周期
-Zpolonius
在 nightly 中,这些原始示例中的每一个都按原样编译:
use std::collections::BTreeMap;
fn do_stuff(map: &mut BTreeMap<i32, i32>, key: i32) -> Option<&i32> {
if let Some(key) = map.get(&key) {
return Some(key);
}
map.insert(0, 0);
None
}
fn find_or_create_five(container: &mut Vec<u8>) -> &mut u8 {
match container.iter_mut().find(|e| **e == 5) {
Some(element) => element,
None => {
container.push(5);
container.last_mut().unwrap()
}
}
}
也可以看看:
关于rust - 从 HashMap 或 Vec 返回引用会导致借用持续超出其所在的范围吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60953543/
假设我有一个组织 ID 向量 let orgs = vec![1, 3, 14, 12]; 然后我调用 .iter()在 each 上获取每个组织的事件,其中函数 get_events_for()返回
这个问题已经有答案了: What are Rust's exact auto-dereferencing rules? (4 个回答) 已关闭 3 年前。 我很困惑为什么这个函数 get适用于 Vec
let a = vec![ vec![1, 2], vec![3, 4], vec![5, 6] ]; 怎么才能聚成一个Vec包含在所有 Vec 中的所有值s 在 a ? 最佳答案 您可以使用 fla
我在HashMap, Vec>中有数据,我想将该数据作为字节缓冲区(单个Vec)写入文件,然后从文件中读取回去并重建HashMap结构。 是否有建立像这样的平坦化和恢复 map 的算法?我可以将元数据
我正在寻找一种“使用rust ”的方式来将 Vec 累积到 Vec 中,以便将每个内部 Vec 的第一个元素加在一起,将每个 Vec 的每个第二个元素加在一起,等等......,并将结果收集到 Vec
我正在寻找一种“使用rust ”的方式来将 Vec 累积到 Vec 中,以便将每个内部 Vec 的第一个元素加在一起,将每个 Vec 的每个第二个元素加在一起,等等......,并将结果收集到 Vec
我正在尝试使用 selection_sort 创建一个已排序的向量,同时保留原始未排序的向量: fn main() { let vector_1: Vec = vec![15, 23, 4,
在 https://doc.rust-lang.org/std/vec/struct.Vec.html#method.iter , 我只能在页面左侧的索引侧边栏中找到iter。但是,找不到 iter_
我正在尝试从 Vec> 创建一个集合向量 ( Vec> ) .这是我目前的进展: use std::collections::BTreeSet; fn main() { // The data
我错过了向量向量初始化的一些东西。在第一种方法中,我尝试了这段代码: let mut landFirst: Vec> = Vec::with_capacity(width); for v in lan
我想设计一个类似于示例 here 的函数除了我的情况,iproduct 的参数数量在编译时是未知的。正如 here 所解释的那样,这在 python 中很容易完成。 . 我已经尝试使用 itertoo
我有一个我不明白的问题: fn cipher_with(key: &[u8], data: &[u8]) -> Vec { let data_len = 16; let mut dat
我刚开始学习 Rust,我偶然发现了这个愚蠢的问题: error: mismatched types: expected `&[u8]` but found `&collections::vec::V
这个问题在这里已经有了答案: How to filter a vector of custom structs? (1 个回答) 关闭 4 年前。 我有一个接受 &Vec 的函数(其中 Word 是
试图创建一个 HashMap 的数据库结构向量。每个Vec包含 Box . use std::collections::HashMap; trait Model { fn id(&self)
我正在编写一个使用 Vec> 的库类型以按列优先顺序存储数据(每个内部 Vec 代表一列)。用户可以创建 Vec>具有任何行和列长度,但所有列都被限制为相同的长度。 有时我需要高效地遍历 Vec>按行
在 GLSL 中我不明白什么是“in”和“out”变量,这是什么意思?这是我从教程中复制的代码示例。 // Shader sources const GLchar* vertexSource =
例如 [[5,6][2,3][2,5][2,9][1,6]]先按第一个元素升序排序,当一个元素相等时,按第二个元素降序排序,得到[1,6],[2,9],[2,5],[2,3] ],[5,6] 最佳答案
我正在尝试为类型为Vec>的向量创建可变的迭代器 迭代器代码: pub struct IterMut { iter: &'a mut Vec>, ix: usize, inne
我是 rust 编程的新手。我想用递归实现合并排序。这是我的代码: fn merge(a: &mut Vec, b: &mut Vec) -> Vec { let mut temp: Vec
我是一名优秀的程序员,十分优秀!