gpt4 book ai didi

rust - 错误[E0502] : cannot borrow `char_array` as mutable because it is also borrowed as immutable

转载 作者:行者123 更新时间:2023-11-29 08:16:10 27 4
gpt4 key购买 nike

我正在编写一个小程序来识别字符串中第一个重复出现的字符:

use std::io;

fn main() {
let mut main_string = String::new();

println!("Please enter the string : ");
io::stdin()
.read_line(&mut main_string)
.expect("Failed to read the input value");

main_string = main_string.trim().to_string();
println!("The trimmed string is : {}", main_string);

let repeating_character = recurring_string_parser(main_string);

println!(
"The character which is first repeating is {}",
repeating_character
);
}

fn recurring_string_parser(main_string: String) -> char {
let mut char_array = Vec::new();
for each_char in main_string.chars() {
let mut some_val = char_array.iter().find(|&&c| c == each_char);

match some_val {
Some(ch) => return each_char,
_ => println!("do nothing"),
}
char_array.push(each_char);
println!(" The charcater is {:?}", some_val);
}

return 'a';
}

错误:

error[E0502]: cannot borrow `char_array` as mutable because it is also borrowed as immutable
--> src/main.rs:31:9
|
25 | let mut some_val = char_array.iter().find(|&&c| c == each_char);
| ---------- immutable borrow occurs here
...
31 | char_array.push(each_char);
| ^^^^^^^^^^ mutable borrow occurs here
32 | println!(" The charcater is {:?}", some_val);
33 | }
| - immutable borrow ends here

我做错了什么?如果有人也能解释一下,那将会很有帮助,因为我发现很难理解可变借用的概念。

最佳答案

char_array.iter().find(|&&c| c == each_char) 的返回类型是一个 Option<&char> ;指向 char_array 中原始项目的引用.然后您尝试修改 char_array这可能会使任何引用无效。之后,您尝试通过打印来访问现在可能无效的值。

在 C 或 C++ 等语言中,此代码是允许的,但偶尔会崩溃、损坏数据、允许任意代码执行或吃掉你的衣服。

最懒惰的解决方案是重新排序 println并在 some_val 周围添加一组额外的大括号应该住(将来我们将拥有非词法生命周期,并且不需要额外的大括号):

{
let mut some_val = char_array.iter().find(|&&c| c == each_char);

match some_val {
Some(ch) => return each_char,
_ => println!("do nothing"),
}
println!(" The character is {:?}", some_val);
}

char_array.push(each_char);

您还可以克隆该值,打破 some_val 之间的关系和 char_array :

let mut some_val = char_array.iter().find(|&&c| c == each_char).cloned();

另见:

关于rust - 错误[E0502] : cannot borrow `char_array` as mutable because it is also borrowed as immutable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47077709/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com