io::stdin()
은 실제로 BufferedReader<>
의 포장 stdin
입니다. 을 볼 수 있듯이 BufferedReader
은 많은 콘텐츠를 추출하는 방법을 제공합니다.
당신은 특히이 : 표준 입력에서 라인을 읽으려고합니다
fn read_line(&mut self) -> IoResult<String>
(그리고 아마도 오류를 반환).
let a: int = from_str(io::stdin().read_line().unwrap().as_slice()).unwrap()
를하지만 오류 처리를하지 않습니다 쉽게 실패 할 수 있습니다 : 간단한 코드는 표준 입력에서 int
이 될 것이다 읽을 수 있습니다.
더 명시 적 접근 방식은 더 깔끔하게 일을 처리 할 필요 :
let a: int = match from_str(
match io::stdin().read_line() {
Ok(txt) => txt, // Return the slice from_str(...) expects
Err(e) => { /* there was an I/O Error, details are in e */ }
}.as_slice()) /* match from_str(...) */ {
Some(i) => i, // return the int to be stored in a
None => { /* user input could not be parsed as an int */ }
};
Rust는'txt'가 두 번째 구현의 다음 블록에서 일치하기에 충분히 오래 살아 있지 않다는 것을 알려주고 있습니다. 어떻게 그걸 지나갈 수 있습니까? –
고정 된 상태로 유지하면 as_slice()가 첫 번째 일치 명령문의 끝으로 이동해야합니다. –
@SyntacticFructose 오 그래, 실제로 잡을 수 있습니다! 나는 그것을 바로 잡을 것이다. – Levans