option_result 0.0.1-dev-2 copy "option_result: ^0.0.1-dev-2" to clipboard
option_result: ^0.0.1-dev-2 copied to clipboard

A lightweight Dart library for Rust-like Option/Result types. Supports exhaustive pattern matching and provides helpers for None()/Err() propagation

option_result #

option_result is a lightweight Dart library for Option and Result types. Inspired by Rust, leveraging Dart 3's new pattern matching features and sealed class exhaustive switch mechanics to provide as close to Rust's Option/Result experience as possible without going so deep as to implement every single utility method Rust provides.

This package is a work-in-progress.

Getting started #

Add the dependency to your pubspec.yaml file in your Dart/Flutter project:

dependencies:
  option_result: ^0.0.1-dev-2

Or via git:

dependencies:
  option_result:
    git: https://github.com/zajrik/option_result.git

Then run dart pub get or flutter pub get and import the library:

import 'package:option_result/option_result.dart';
// or import the separate types individually:
import 'package:option_result/option.dart';
import 'package:option_result/result.dart';

Basic Usage #

// Assume getUser() returns some sort of User object
Result<User, String> user = await getUser(id: 12345);

if (user case Err(value: String error)) {
  print('Error retrieving user: $error');
  return;
}

// Assume the User object has an email field of type Option<String>
Option<String> email = user.unwrap().email;

if (email case Some(value: String address)) {
  print('User email: $address');
} else {
  print('User has no email set.');
}

// Alternative to the above using a switch expression for pattern matching
print(switch (email) {
  Some(value: String address) => 'User email: $address',
  None() => 'User has no email set.'
});

// Pattern matching with switch is exhaustive for Option and Result, so the compiler
// will give you warnings/errors to make sure you're providing cases for all potential
// values for Ok()/Some(), either directly or via a default case, and for Err()/None(),
// again either directly or via a default case

Additional information #

This library was written largely because I didn't like the way other libraries with similar goals would leverage higher-order functions for faux-pattern-matching. Now that Dart has real pattern matching I wanted to use something that leverages that, but couldn't find anything that really fit my needs, nor my appreciation of Rust's implementation.

13
likes
0
pub points
59%
popularity

Publisher

unverified uploader

A lightweight Dart library for Rust-like Option/Result types. Supports exhaustive pattern matching and provides helpers for None()/Err() propagation

Repository (GitHub)
View/report issues

License

unknown (license)

More

Packages that depend on option_result