I'm writing some Rust code to practice and I try to do it idiomatically with Result (The Book Chap IX )
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 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.
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.