It's a piece of homework to get the longest substring of consecutive equal characters.
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"));
}
I expected the output to be
in Some("cccc")
out Some("cccc")
but got a compilation error.
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 | | }
| |_^
error: aborting due to previous error
If returning None instead of some, the code compiles and runs as you would expect:
in Some("cccc")
out None
I got confused because the error message is pointing to a line before this change..
Can someone help? Thanks.
P.S.: I changed it to record the start and end position indices, so that I can return Some(&s[start..end]). I thought s should definitely have enough lifetime, and yeah it works! but I still want to know why the above implementation doesn't work..