Search code examples
rustrust-obsolete

Getting basic input for ints


I'm quite surprised I can't seem to navigate rust's documentation to find any case that describes io, could someone please explain to me how to use basic io to get user input into say, an integer? And maybe where to find the io details in that accursed documentation? Thanks


Solution

  • To answer your question about ints. (All of these type annotations are optional, and I've separated things out each step.)

    use std::io;
    
    fn main() {
        let mut stdin = io::stdin();
    
        let err_line: io::IoResult<String> = stdin.read_line();
        let line: String = err_line.unwrap();
    
        let line_no_extra_whitespace: &str = line.as_slice().trim();
        let possible_number: Option<int> = from_str(line_no_extra_whitespace);
    
        match possible_number {
            Some(n) => println!("double your number is {}", 2 * n),
            None => println!("please type an integer")
        }
    }
    

    Documentation (NB. almost all types in the docs are clickable, taking you to a page with more description/listing what you can do with them):

    Also, note that the docs are searchable, via the search box at the top of the page, e.g. searching for "stdin". (You can press 's' on any page to jump to the search box, ready to type.)


    You might also be interested in this answer about the difference between the heap allocated String and the string slice &str.

    Others have pointed out the cheatsheet, the entry point for the docs std, and the IO-specific std::io. There's other places with nice information, like the std::result text, for working with the return values from IO operations (remember IoResult is a Result and so supports all those operations), and the #rust IRC channel on irc.mozilla.org (web client) normally has multiple people willing to help.