Monday, August 15, 2022

Answer to Rust quiz 2: summer

Answer to the Rust quiz 2: summer

Lines 1-10:

// Influenced by the following stacks:

// https://stackoverflow.com/questions/27043268/convert-a-string-to-int
// https://stackoverflow.com/questions/23100534/how-to-sum-the-values-in-an-array-slice-or-vec-in-rust

use std::env;

fn main() {
   let args: Vec<_> = env::args().collect();
   let (_, args) = args.split_at(1);

Q: Aren't these lines the same as in the first chapter?
A: Yes

Q: So, can we put this code into a library, or something, instead of having to write for each new program?
A: Exactly! Not for this program, but the next program will be about writing your own modules.

Lines 12-15:

let nums: Vec<f32> =
  args.iter()
  .map(|n| n.parse().expect(&(n.to_owned() + " isn't a number")))
  .collect();

Q: Line 12 we saw in ch 1, what does line 13 do?
A: converts args into an iterable object, a stream; you see this also in line 16.

Q. map who-the-what?
A. Let's work through this:
  • map maps a function over a stream.
  • |n| creates a function that takes an argument, n
  • the function parses n, expecting it to be a number
  • if n isn't, it throws an error with a message saying it isn't a number.
EASY!

Q. line 15 collects ... what?
A. collect collects the result from a stream into the, well, collection-type you've declared (in this case, a vec(tor) of f32 numbers).

Q. What's the 'f' in f32?
A. Eheh. No, it's a 'float'ing point number. Really: that's what the 'f' stands for. 

Line 16:

let sum: f32 = nums.iter().sum();
Q. iter puts the collection to a stream, sum sums the stream. No collect?
A. You don't need to collect when you're getting a single value (or 'scalar,' or not a vector) as a result.

Line 17:


println!("The sum of {:?} is {:?}", nums, sum);

Q. What does the "{:?}" mean?
A. It means "print the value of this type, even though I don't know [or, in my case 'I don't care'] what that type is."

Q. Oh. Then why don't you use it all the time?
A. Sometimes you don't have to.

Q. Like, when?
A. Like, when you know it's a string, you can just use "{}" and for other simple types (like numbers), you can use their "{:type}" representation.

Q. So, when do you use "{:?}"?
A. When the type is complex so that an accurate type-representation is more work than printing the thing, or, when I don't know the type at runtime (or I don't care what the type is).

Q. How does it know which value to put into the first and second "{:?}"? And that there are two values to add to the string printed out?
A. I'll punt to: "that's why println! is a macro." The macro allows the system to determine the arguments to the format-string, automagically.

No comments:

Post a Comment