The error message gives useful hints on what to do:
frequently replaced by the
chars()iterator, this method may be removed or possibly renamed in the future; it is normally replaced bychars/char_indicesiterators or by getting the first char from a subslice (see issue #27754)
-
We could follow the error text:
for line in lines_of_text.split("\n") { match line.chars().next() { Some('#') => println!("Heading"), Some('>') => println!("Quotation"), Some('-') => println!("Inline list"), Some('`') => println!("Code"), Some(_) => println!("Other"), None => println!("Empty string"), }; }Note that this exposes an error condition you were not handling! What if there was no first character?
-
We could slice the string and then pattern match on string slices:
for line in lines_of_text.split("\n") { match &line[..1] { "#" => println!("Heading"), ">" => println!("Quotation"), "-" => println!("Inline list"), "`" => println!("Code"), _ => println!("Other") }; }Slicing a string operates by bytes and thus this will panic if your first character isn’t exactly 1 byte (a.k.a. an ASCII character). It will also panic if the string is empty. You can choose to avoid these panics:
for line in lines_of_text.split("\n") { match line.get(..1) { Some("#") => println!("Heading"), Some(">") => println!("Quotation"), Some("-") => println!("Inline list"), Some("`") => println!("Code"), _ => println!("Other"), }; } -
We could use the method that is a direct match to your problem statement,
str::starts_with:for line in lines_of_text.split("\n") { if line.starts_with('#') { println!("Heading") } else if line.starts_with('>') { println!("Quotation") } else if line.starts_with('-') { println!("Inline list") } else if line.starts_with('`') { println!("Code") } else { println!("Other") } }Note that this solution doesn’t panic if the string is empty or if the first character isn’t ASCII. I’d probably pick this solution for those reasons. Putting the if bodies on the same line as the
ifstatement is not normal Rust style, but I put it that way to leave it consistent with the other examples. You should look to see how separating them onto different lines looks.
As an aside, you don’t need collect::<Vec<_>>().iter(), this is just inefficient. There’s no reason to take an iterator, build a vector from it, then iterate over the vector. Just use the original iterator.