I am writing a small program to identify the first recurring character in a string:
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:
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
What is it that I am doing wrong? It would be of great help if someone could explain it as well because I am finding it difficult to grasp the concept of mutable borrowing.