Page MenuHomeDevCentral

Implement a similar datatype than Rust result
Changes PlannedPublic

Authored by dereckson on Sep 2 2018, 00:02.
Tags
None
Referenced Files
Unknown Object (File)
Thu, Jul 25, 01:41
Unknown Object (File)
Wed, Jul 24, 17:31
Unknown Object (File)
Wed, Jul 24, 17:31
Unknown Object (File)
Wed, Jul 24, 16:31
Unknown Object (File)
Sat, Jul 20, 11:32
Unknown Object (File)
Mon, Jul 15, 22:29
Unknown Object (File)
Mon, Jul 15, 10:59
Unknown Object (File)
Sun, Jul 14, 06:52
Subscribers
None

Details

Reviewers
dereckson
Summary

When a library needs to communicate an error status, to be handled
only by an initial caller down in the task or a success, the Result
generic type from the Rust library is convenient.

If PHP doesn't have the generics and Rust-like enum, we can at least
provide a base class Result, with two concrete implementations:

  • Err for exceptions
  • Ok for actual values

Reference:
https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html

Test Plan

Implement in Zed story engine

Diff Detail

Repository
rKOT Keruald OmniTools
Lint
Lint Passed
Unit
Tests Passed
Branch
Result (branched from master)
Build Status
Buildable 2601
Build 2849: arc lint + arc unit

Event Timeline

dereckson created this revision.

Some ideas to make this code more useful:

  • a constructor to allow new Ok(42)
  • implement map methods:
    • or_else(defaultValue) -> return defaultValue for Err, $this->value for Ok
    • map() -> no op for Err, change value allowing type mutability for Value
    • map_err() -> no op for Value, change value allowing any Exception for Err

In PHP 8.1, could be interesting to do this:

Result sample use
use Keruald\OmniTools\DataTypes\Result;
use Keruald\OmniTools\DataTypes\ResultShape;

#[ResultShape(string, string)]
function doSomething() : Result {
    return ...;
}

$result = match (doSomething()) {
    $result->isOk() => $result->getValue(),
    default => throw new RuntimeException($result->getError()),
};

For this to work, we need two things:

  • Declare getError() in Result too
  • A ResultShape attribute to be able to typehint the Result