mojo icon indicating copy to clipboard operation
mojo copied to clipboard

[Feature Request] [stdlib] [proposal] Add `ErrorReg`, `Result`, and `ResultReg` types

Open martinvuyk opened this issue 9 months ago • 0 comments

Review Mojo's priorities

What is your request?

Result is basically a copy paste of Optional just with an error attribute.

"""Defines Result, a type modeling a value which may or may not be present. With an Error in the case of failure.

Result values can be thought of as a type-safe nullable pattern. Your value can take on a value or None, and you need to check and explicitly extract the value to get it out.

from collections import Result
var a = Result(1)
var b = Result[Int]()
if a:
    print(a.value()[])  # prints 1
if b:  # bool(b) is False, so no print
    print(b.value()[])
var c = a.or_else(2)
var d = b.or_else(2)
print(c)  # prints 1
print(d)  # prints 2

And if more information about the returned Error is wanted it is available.

from collections import Result
var a = Result(1)
var b = Result[Int](err=Error("something went wrong"))
var c = Result[Int](err=Error("error 1"))
var d = Result[Int](err=Error("error 2"))
if a:
    print(a.err)  # prints ""
if not b:
    print(b.err) # prints "something went wrong"

if c.err:
    print("c had an error")

# TODO: pattern matching
if d.err == "error 1":
    print("d had error 1")
elif d.err == "error 2":
    print("d had error 2")

A Result with an Error cal also be retuned early:

fn func_that_can_err[A: CollectionElement]() -> Result[A]:
    ...

fn return_early_if_err[T: CollectionElement, A: CollectionElement]() -> Result[T]:
    var result: Result[A] = func_that_can_err[A]()
    if not result:
        # the internal err gets transferred to a Result[T]
        return result
        # its also possible to do:
        # return None, Error("func_that_can_err failed")
    var val = result.value()
    var final_result: T
    ...
    return final_result

What is your motivation for this change?

Better Error handling than raising and giving people tools to write nicer code

Any other details?

I skimmed over the Error struct's code and it seems it can be done replacing its fields with just a StringLiteral (?)

martinvuyk avatar May 18 '24 22:05 martinvuyk