-1

For Reference: I am a Java programmer who is brand new to Rust

I am trying to read a file that has 2 inputs being size of array, and elements of array.

Input:

3
1 2 3

I want to make a function that reads in a file through arguments in command line so I wrote the following code: (Note: it is super ugly as I was changing up the function)

fn getArraySize() -> usize
{
    let args: Vec<String> = env::args().collect();

    let input = File::open(&args[1])?;
    let buffered = BufReader::new(input);

    let mut counter: i32 = 0;
    let arraySize: usize = 0;
    for line in buffered.lines() {
        if counter == 0
        {
            let line = String::from(line?);
            arraySize = line.parse().unwrap();
            println!("{}", arraySize);
            counter += 1;
        } 
    }
    arraySize
}

Which is a function that sets a const value

const ARRAYSIZE: usize = getArraySize();

My problem is that I just cannot seem to figure out how to get this line to work

let input = File::open(&args[1])?;

I tried attaching .expected to it, but nothing happened. I tried everything I could find on Google, but without global variables I can change, I don't know how to get the file such that my function can read it and return arraySize.

BadCoder
  • 141
  • 1
  • 16
  • 2
    Other than the fact that you need to handle runtime errors (`?` just propagates them, but they need to be handled at some point), you have a deep misunderstanding of what `const` means, as eg. using `File` or `env::args()` in a `const` function makes no sense whatsoever. – mcarton Feb 09 '20 at 23:24
  • 1
    Please provide a **complete** [mcve]. – Stargateur Feb 10 '20 at 05:14
  • 1
    The Java equivalent would be putting `throw new CheckedException()` in a function that is not declared as `throws CheckedException`. – trent Feb 10 '20 at 13:14

2 Answers2

6

You can think of the ? syntax used here:

let input = File::open(&args[1])?;

As a shortcut for this (more or less - haven't tested this code):

let input = match File::open(&args[1]) {
    Ok(input) => input,
    Err(e) => return Err(e),
};

Let's say that File::open returns Result<T, E> - for the second snippet of code to work, the containing function must return Result<U, E> where T may or may not be U. If this was not the case, then the return Err(...) would be an invalid value to return.

mcarton
  • 27,633
  • 5
  • 85
  • 95
Luke Joshua Park
  • 9,527
  • 5
  • 27
  • 44
2

Rust - ? can only be used in a function that returns Result

This is not correct, ? can be used for any return type that implements Try trait. You can implement this to your own structure, here is the examples from std:

impl<T> Try for Option<T>
impl<T, E> Try for Result<T, E>
impl<T, E> Try for Poll<Option<Result<T, E>>>
impl<T, E> Try for Poll<Result<T, E>>
Ömer Erden
  • 7,680
  • 5
  • 36
  • 45
Stargateur
  • 24,473
  • 8
  • 65
  • 91