Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 398
Syntactic Fructose Avatar asked May 28 '26 21:05

Syntactic Fructose


1 Answers

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):

  • stdin
  • .read_line
  • IoResult (note that is just renaming the type, that is, it is actually a Result.)
  • String
  • .unwrap
  • from_str (and the FromStr trait which it wraps.)
  • .as_slice (you can see String in the list of implementers.)
  • .trim
  • Option (None and Some are the two variants of Option)
  • println!

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.

like image 133
huon Avatar answered May 31 '26 19:05

huon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!