rust_core 0.2.0 rust_core: ^0.2.0 copied to clipboard
Implementation of Rust's core library in a Dart friendly way. Usable by itself, but also a base for libraries that want to build on Rust Semantics.
Rust Core #
Implementation of Rust's core library in a Dart friendly way.
Panic
Rust vs Dart Error handling terminology:
Dart Exception Type | Equivalent in Rust |
---|---|
Exception | Error |
Error | Panic |
Thus, here Error
implements Dart core Exception
(Not to be confused with the
Dart core Error
type)
import 'package:anyhow/anyhow.dart' as anyhow;
import 'package:anyhow/base.dart' as base;
base.Result<String,anyhow.Error> x = anyhow.Err(1); // == base.Err(anyhow.Error(1));
And Panic
implements Dart core Error
.
if (x.isErr()) {
return x.unwrap(); // this will throw a Panic (should be "unwrapErr()")
}
As with Dart core Error
s, Panic
s should never be caught.
Anyhow was designed with safety in mind. The only time anyhow will ever throw is if you unwrap
incorrectly (as above),
in
this case it will throw a Panic
. See How to Never Unwrap Incorrectly section to
avoid ever using unwrap
.
Null and Unit
In Dart, void
is used to indicate that a function doesn't return anything or a type should not be used, as such:
Result<void, void> x = Ok(1); // valid
Result<void, void> y = Err(1); // valid
int z = x.unwrap(); // not valid
Since stricter types are preferred and Err
cannot be null:
Result<void, void> x = Ok(null); // valid
Result<void, void> x = Err(null); // not valid
Therefore use ()
or Unit
:
Unit == ().runtimeType; // true
Result<(), ()> x = Err(unit); // valid
Result<Unit, Unit> y = Err(()); // valid
x == y; // true
// Note:
// const unit = const ();
// const okay = const Ok(unit);
// const error = const Err(unit);
Infallible
Infallible
is the error type for errors that can never happen. This can be useful for generic APIs that use Result
and parameterize the error type, to indicate that the result is always Ok.Thus these types expose intoOk
and
intoErr
.
Result<int, Infallible> x = Ok(1);
expect(x.intoOk(), 1);
Result<Infallible, int> w = Err(1);
expect(w.intoErr(), 1);
typedef Infallible = Never;
See examples for more.