Ok() and Error() and match statements

use std::io;

fn main()
{
    let mut input = String::new();

    match io::stdin().read_line(&mut input)
    {
        Ok(_) => println!("input: {}", input),
        Err(_) => println!("Error!"),
    }
}

So with this program, I am a bit confused with Ok(_) and Err(_) inside the match statement. So with the match statement, this line io::stdin().read_line(&mut input), does it output something? Cause like I tried to print this but I got an error.

So what is it exactly outputting? Does it output Ok(_) if it ran fine? Also with the function Ok(_), if I don't want to pass in the byte size b to retrieve how many bytes my input was, then how come the Ok() function accepts _ this argument?

read_line returns a Result. Read more about the Result type in the book.

The underscore _ is a special pattern that matches any value, and ignores it. You can use it whenever you don't care about the contents of the thing you are matching.

2 Likes

Okay it seems you have misconceptions about what's going on here.
Look at the result enum, here Result<T, E>

Ok and Err aren't functions. they are variants of an enum

pub enum Result<T, E> {
    Ok(T),
    Err(E),
}

rust doesn't have errors and nulls. It has Result and Option to deal with those.

Assume there's a function that returns a String but might also be an error. It's return type would be Result<String, SomeError>

fn string_function() -> Result<String, SomeError>(){
    //
}

you can use the result like this

let string_result = string_function();
match string_result {
    Ok(my_string) => println!("{}", my_string),
    Err(some_error) => println!("{}", error),
}

my_string and some_error are just variable names you defined. _ just means you don't want the value and want to throw it away.

It's best if you read up on Enums and Pattern matching in rust, Especially Option and Result.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.