fn main(){ let strr="Hello"; println!("{:?}",strr.chars().nth(0)); }
"After compiling and running, I get Some ('H'). How to get (just an index without extraneous characters) H without Some ()?"
I generally lose weight from such issues. Information:
Option is an analogue of null , its safe version. Ie if the index 0 in the string does not exist will return None , and if the index exists, then there will be Some('') . Option itself is enum having either Some or None .
Chars nth method https://doc.rust-lang.org/std/str/struct.Chars.html
fn nth(&mut self, n: usize) -> Option<Self::Item>[src] //ВОЗВРАТ OPTION Returns the nth element of the iterator.
How to handle Option ??
fn main() { let test_str = "Hello"; let mut test_chars = test_str.chars(); if let Some(a) = test_chars.nth(0) { //ЕСЛИ ФУНКЦИЯ ВЕРНУЛА OPTION::SOME(A) то println!("{:?}", a); } //НО НЕ ПРОВЕРЯЕТСЯ ЕСЛИ ИНДЕКСА 0 В СТРОКЕ НЕ СУЩЕСТВУЕТ }
Running: https://play.rust-lang.org/?gist=d543bbf77e8ad87976246753bedd69df&version=stable
fn main() { let test_str = "Hello"; let mut test_chars = test_str.chars(); match test_chars.nth(0) { Some(a) => { println!("{:?}", a); }, None => { println!("Индекса 0 в строке test не существует. Спасибо за внимание."); } } //Этот пример мне нравится больше, в нем вы можете реагировать на отсутствие индекса, или на его присутствие. И намного лучше еслиб вы в прошлом примере писали else к if. }
Running: https://play.rust-lang.org/?gist=586bac28433d519d5771269441a351de&version=stable
Bad example:
fn main() { let test_str = "Hello"; let mut test_chars = test_str.chars(); let char_a = test_chars.nth(0).unwrap(); println!("{:?}", char_a); }
Running: https://play.rust-lang.org/?gist=c87388771277e5337ded6d38c56fdee6&version=stable
Describe the response to the absence of an index better than using unwrap. Unwrap says if you returned Some (a) then write 'a' to a variable, and if index 0 does not exist, then abort the program.
Tip: Do not use the NTH method for such purposes as getting a string index. Bear in mind that it works for a slightly different purpose.
fn nth(&mut self, mut n: usize) -> Option<Self::Item> { for x in self { if n == 0 { return Some(x) } n -= 1; } None }
For such purposes it is well suited: (but it returns exactly str)
fn main() { let strr="Hello"; if let Some(a) = strr.get(0..1){ println!("{:?}", a); } }
Running: https://play.rust-lang.org/?gist=dc781ddb6e6d3441125a2f6a8d7162e6&version=stable
.nth(0).unwrap()? - VTTchar_indices()method. - mzabaluev