texthtml/result-option

用于您函数返回值的类型:结果和选项。

dev-master 2020-08-22 01:00 UTC

This package is auto-updated.

Last update: 2024-09-22 09:54:05 UTC


README

用于您函数返回值的类型:结果和选项。

Result 类型用于返回和传播错误。它可以是 Ok(T),表示成功并包含一个值,或者是 Error(E),表示错误并包含一个错误值。

Type Option 代表一个可选值:每个 Option 要么是 Some 并包含一个值,要么是 None,不包含任何值。Option 类型有许多用途

  • 初始值
  • 对于在其整个输入范围内未定义的函数(部分函数)的返回值
  • 在报告简单错误时的返回值,其中错误时返回 None
  • 可选类属性
  • 可选函数参数
  • 可空值

Option 是用于一个值要么包含 T,要么不包含任何值的类型。

Result 使用方法

完整的 API 文档

声明并编写返回 Result 的函数

/**
 * @return Result<string,string>
 */
function readFile(string $path): Result
{
    return match ($content = file_get_contents($path)) {
        false => Result::error("file at $path could not be read"),
        default => Result::ok($content),
    };
}

使用 Result

检查结果是否为错误

$content = readFile("/path/to/file");

if ($content->isError()) die("{$content->unwrapError()}" . PHP_EOL);

echo $content->unwrap();

处理结果

/**
 * @param Result<string,string>
 * @return Result<int,string>
 */
function length(Result $o): Result
{
    return $o->map("strlen");
}

Option 使用方法

声明并编写返回 Option 的函数

/**
 * @return Option<string>
 */
function firstChar(string $s): Option
{
    return match (true) {
        $s === "" => Option::none(),
        default   => Option::value($s[0]),
    };
}

使用 Option 值

检查结果是否为错误

$c = firstChar("Option");

if ($c->isNone()) die("There is no first character in the string" . PHP_EOL);

echo "firstChar(\"Option\") = {$c->unwrap()}", PHP_EOL;

处理结果

/**
 * @param Option<int>
 * @return Option<bool>
 */
function even(Option $o): Option
{
    return $o->map((int $i) => $i % 2 === 0);
}