Rust, lesson 3
Your programs in this course read from standard input (stdin) and print to standard
output. Rust's standard library puts input tools in the std::io module.
Step by step:
use std::io; lets you write io::stdin() instead of std::io::stdin().String::new() makes an empty, growable string. It must be mut because read_line
will add text to it.&mut line lends the string to read_line so it can write into it. Lesson 14 explains
borrowing properly; for now, read as "you may change this".2 exercises to try what you just read.
&mutread_line keeps the newline at the end, so trim() removes surrounding whitespace.read_line returns a Result. expect gives you the value on success
and stops the program with your message on failure.When the input has many numbers spread over lines, it is often simplest to read it all and split on whitespace:
split_whitespace gives the pieces one at a time. next() returns the next piece wrapped in
an Option (it might have run out), and unwrap() takes it out. unwrap is like expect
without a custom message.
parse converts a string to another type. It needs to know the target type, which you give
with an annotation (let n: i32 = ...) or with the "turbofish" syntax: "42".parse::<i32>().
Parsing returns a Result because the text might not be a number. In lesson 9 you will handle
that properly; for now unwrap() is fine.
| Operator | Meaning | 7 ? 2 with integers |
|---|---|---|
+ | add | 9 |
- | subtract | 5 |
* | multiply | 14 |
/ | divide | 3 |
% | remainder | 1 |
Integer division drops the fraction: 7 / 2 is 3. For 3.5, use floats: 7.0 / 2.0, or
convert with as f64. Both sides of an operator must have the same type; 5_i32 + 2.0 is
a compile error.
Compound assignment works as you would expect: x += 1, x *= 2. Rust has no ++ or --.
Numbers have useful methods: n.abs(), n.pow(3), x.sqrt(), x.round(), and
a.max(b) / a.min(b).
Friends share a restaurant bill equally. Read the bill total (a decimal number) and the number of people (a whole number), separated by whitespace. Print what each person pays with exactly two decimals.
Sample input:
Sample output:
A race timer records a run in whole seconds. Read one integer and print it as H:MM:SS, where
minutes and seconds always have two digits.
Sample input:
Sample output:
use std::io;
fn main() {
let mut line = String::new();
io::stdin().read_line(&mut line).expect("failed to read");
let name = line.trim();
println!("Hello, {name}!");
}let input = io::read_to_string(io::stdin()).unwrap();
let mut words = input.split_whitespace();
let a: i64 = words.next().unwrap().parse().unwrap();
let b: i64 = words.next().unwrap().parse().unwrap();
println!("{}", a + b);println!("{:.2}", 10.0 / 3.0); // 3.33
println!("{}:{:02}", 7, 5); // 7:0585.00 328.3337251:02:05