Voglio controllare se una stringa inizia con alcuni caratteri:Qual è il modo corretto e idiomatico per verificare se una stringa inizia con un certo carattere in Rust?
for line in lines_of_text.split("\n").collect::<Vec<_>>().iter() {
let rendered = match line.char_at(0) {
'#' => {
// Heading
Cyan.paint(*line).to_string()
}
'>' => {
// Quotation
White.paint(*line).to_string()
}
'-' => {
// Inline list
Green.paint(*line).to_string()
}
'`' => {
// Code
White.paint(*line).to_string()
}
_ => (*line).to_string(),
};
println!("{:?}", rendered);
}
ho usato char_at
, ma segnala un errore a causa della sua instabilità.
main.rs:49:29: 49:39 error: use of unstable library feature 'str_char': frequently replaced by the chars() iterator, this method may be removed or possibly renamed in the future; it is normally replaced by chars/char_indices iterators or by getting the first char from a subslice (see issue #27754)
main.rs:49 let rendered = match line.char_at(0) {
^~~~~~~~~~
Attualmente sto usando Rust 1.5
Perfetto. Grazie! – rilut
Sì, pensavo che anche la raccolta sul vettore fosse inefficiente. Non sapevo che Split fosse lo stesso iteratore di iter. Posso chiederti, che è più veloce dalle tue soluzioni? O la loro velocità è più o meno la stessa? – rilut
@rilut puoi chiedere, ma non so la risposta^_ ^. Forse qualcuno interverrà, ma potresti anche fare alcuni test delle prestazioni nella tua app e vedere di sicuro. Probabilmente * suppongo * che siano tutti uguali. – Shepmaster