I’m just getting up to speed with rust. As an exercise I’m trying to recreate strtok()
in rust. However I’m stuck with correcting the types..
Here’s what I have (Live Demo):
fn strtok(str: Option<&'static str>, delimiter: char) -> &'static str {
// Remember the string slice for next time
let temp_str = "";
let mut static_view: &mut &'static str = temp_str;
if str.is_some() {
static_view = str.unwrap();
}
// Get token from start to delimiter
let index = static_view.find(delimiter).unwrap();
let token = &static_view[..index];
static_view = &static_view[index..];
token
}
fn main() {
let str: &str = "Hello World, you son of a bitch!";
let token1 = strtok(Some(str), ',');
let token2 = strtok(None, ',');
println!("{}", token1);
println!("{}", token2);
}
I wanted to create a mutable static reference to a static string (slice), so I could switch the string slice for a different one if provided. If not, the function should go off the last known string slice.
However, I get this error:
error[E0308]: mismatched types
--> src/main.rs:5:46
|
5 | let mut static_view: &mut &'static str = temp_str;
| ----------------- ^^^^^^^^ types differ in mutability
| |
| expected due to this
|
= note: expected mutable reference `&mut &'static _`
found reference `&_`
Which I don’t really understand. I never asked for the slice to be mutable, but I want the reference to it be mutable so I can reassign it. How should