How would you interpret Ok() / Err()

Hi Rustaceans !

I'm writing some Rust code to practice and I try to do it idiomatically with Result (The Book Chap IX :smile: )

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

My goal is a useless CLI application that convert a file to its base32 representation, as does base32 binary on my linux distribution :roll_eyes: I write a function that returns a Result:

   pub fn file_to_base32(filename: &str) -> Result<MyOk, MyError> { 
      /* Boring things here */

        let ok = MyOk { result: true };
        Ok(ok)
 }

The function is not my problem, the last line is. I understand here that the function returns a Result of Ok type, but I'm not clear about interpretation of the Ok(...)/Err(...) thing. It looks like a function call who basically acts like a structure specifier or builder.

Knowing nothing I would expect something like this, without return as Rust is an expression language:

ok as Ok  // Casting ok to Ok type and returning it.
          // Or
Ok{ok}    // Building an Ok with my ok variable and returning it.

How should I read or interpret the Ok(...)/Err(...) expression ?
I could just continue like this since it works, but I just can't memorize something that I don't understand.
Many thanks !

Ok(ok) is equivalent to Result::Ok(ok). The variants of the Result enum are exported by the std prelude, so you don't have to qualify it fully every time. So you should think of it as an enum variant constructor, (which happens to also be a function in this case, because you're constructing a tuple variant.)

Note that this is the same for Option, in that you can also construct it with Some and None without qualification.

You can read more about enums in the book.

3 Likes

There are three variants of enums and structs in Rust: ones with named fields, ones with positional fields, and ones with no fields.

When you see Enum::Foo, that’s a variant with no fields, Enum::Foo { bar: baz } is a variant with one named field, and Enum::Foo(bar) is a variant with one positional field.

There are more examples here: Defining and Instantiating Structs - The Rust Programming Language

So Result::Ok(value) is constructing the Ok variant of the Result enum, which has a single positional field.

2 Likes

Thanks for your complementary answers. I had already read these part of the book, but I didn't remember about building enum like this:

    let home = IpAddr::V4(String::from("127.0.0.1"));

    let loopback = IpAddr::V6(String::from("::1"));

Enums are quite deeper in Rust than other language, my fault. Thanks for your help.

2 Likes

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.