I have a piece of homework to get the longest substring of consecutive equal characters with the signature fn(s: &str) -> Option<&str>
. However, my attempt yields a compiler error:
pub fn longest_sequence(s: &str) -> Option<&str> {
let s_len = s.len();
if s_len == 0 {
return None
}
let mut cur_char = s.chars().nth(0);
let mut cur_occ = 0;
let mut max_char = s.chars().nth(0);
let mut max_occ = 0;
for i in 0..s_len {
let c = s.chars().nth(i);
if c == cur_char {
cur_occ = cur_occ + 1;
} else {
if cur_occ > max_occ {
max_occ = cur_occ;
max_char = cur_char;
}
cur_char = c.clone();
cur_occ = 1;
}
}
if cur_occ > max_occ {
max_occ = cur_occ;
max_char = cur_char;
}
let cr = max_char.unwrap();
let charstr = cr.to_string();
let string = charstr.repeat(max_occ);
let strr = string.as_str();
let some = Some(strr.clone());
println!("in {:?}",some);
some // Compilation error
// None // if returning None, then it compiles and runs as expected
}
fn main () {
println!("out {:?}",longest_sequence(&"aaabbbcccc"));
}
error[E0597]: `string` does not live long enough
--> r.rs:31:16
|
31 | let strr = string.as_str();
| ^^^^^^ borrowed value does not live long enough
...
35 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 1:1...
--> r.rs:1:1
|
1 | / pub fn longest_sequence(s: &str) -> Option<&str> {
2 | | let s_len = s.len();
3 | | if s_len == 0 {
4 | | return None
... |
34 | | some
35 | | }
| |_^
If I return None
instead of some
, the code compiles and the output is as you would expect:
in Some("cccc")
out None
How can I make this work? Can someone help me understand the issue?