What's the best way to return Result<(), _>?

I am creating a program in which main returns Result<(), _>, and I was wondering: what's the best - or rather, most semantic - way to return Ok(())? Should it be as in:

fn main() -> Result<(), std::io::Error> {
    Ok(foo())
}

or as in

fn main() -> Result<(), std::io::Error> {
    foo();

    Ok(())
}

Or is there some other layer to this that I am completely missing?

Thanks!

The second one is considered the best.

2 Likes

For clarification: I believe the second is best because it requires less refactoring in the event more code is added to the function.

On the other hand, the first example may be preferable if foo is local, since if the return type changes it becomes a compile error. That could catch some annoying API problems in some situations.

1 Like

fn main() -> Result<(), std::io::Error> {
    foo()?; 

    Ok(())
}

Just foo() at the end should be sufficient in the case.

Can foo() error? If foo() can have errors, then foo() should return Result<(),_> and your main should just end in foo()

1 Like