#Why are there question marks before the semicolons in this example

1 messages · Page 1 of 1 (latest)

brazen scaffold
#

I was reading through the Rust docs as I want to read a binary file, and I found this example:

use std::io;
use std::io::prelude::*;
use std::fs::File;

fn main() -> io::Result<()> {
    let mut f = File::open("foo.txt")?;
    let mut buffer = [0; 10];

    // read up to 10 bytes
    let n = f.read(&mut buffer[..])?;

    println!("The bytes: {:?}", &buffer[..n]);
    Ok(())
}

(1) Why are there question marks before the semicolons? Also, when it says let mut buffer = [0; 10];, I presume the 10 is the array size, but what is the 0; in it? Bonus: what is the Ok(()) at the end (it doesn't have a semicolon for some reason...)

Example is here: https://doc.rust-lang.org/std/io/trait.Read.html#examples-1

outer quartz
#
  1. ? is shorthand syntax, intended for union enums, which tells Rust you either want to unwrap a value contained in the enum and continue with the function, or propagate the other as the return value of the function. In this case, any errors when opening or reading the file, would be propagated out of the app, resulting in it closing.

  2. [T; N] syntax is used to initialise an array with a uniform set of values (T), with the specified length (N), in this case, being 0ed.

  3. The example has specified that the return type from main() should be an io::Result (a shorthand alias of the normal Result<T, E> type, as a shorthand for IO functions, by defining E as the concrete type, io::Error), and the app needs to exit with a value of this being returned, hence the Ok(()) on the last line, indicating the app closed with no issue, if it reached this point.

rigid wharf
#

It unwraps if it can. Otherwise, it returns the None or Err.