rust_like_result 1.0.3 copy "rust_like_result: ^1.0.3" to clipboard
rust_like_result: ^1.0.3 copied to clipboard

outdated

The Result<T> type implemented in Ok<T> and Err<T> types with unwrap methods.

example/example.dart

import 'package:rust_like_result/rust_like_result.dart';

void main() {
  // Alice (has good answer):
  // Type annotations here are for demonstrate purpose only:
  Result<Map<String, String>> theAliceResult = getMap('Alice');

  // Checking is ok via method before access to value:
  if (theAliceResult.isOk) {
    // Here it is safety to use val for access to underlining value:
    print('theAliceResult isOk and has Map: ${theAliceResult.val}');
  }

  // Checking is ok via type checking:
  if (theAliceResult is Ok) {
    print('theAliceResult is Ok and has Map: ${theAliceResult.val}');
  
  }
  // Unwrap value if result is ok OR raise error if it was Err:
  var mapOrRaising = theAliceResult.unwrap;

  // Black Queen (has bad answer):
  Result<Map<String, String>> queenResult = getMap('BlackQueen');
  // Checking is err via method:
  if (queenResult.isErr) {
    print('queenResult has error. ${queenResult.err}');
    print('Value of queenResult is null, yes? : ${queenResult.val}');
  }  
  
  // Checking is err via type checking:
  if (queenResult is Err) {
    print('queenResult has error. ${queenResult.err}');
    print('Value of queenResult is null, yes? : ${queenResult.val}');
  }

  // Unwrap value if result is ok OR return default value:
  var defaultMap = queenResult.unwrapOrDefault({'Forward': 'Why?'});
  print('defaultMap: $defaultMap');

  // Unwrap value if result is ok 
  // OR return result of calling of function with Error e argument:
  var lazyDefMap = queenResult.unwrapOrElse((e) => {'Forward': 'Hm...'});
  print('lazyDefMap: $lazyDefMap');
}

/// Returns Map for Alice only.
Result<Map<String, String>> getMap(String name) {
  Result<Map<String, String>> result;
  if (name == 'Alice') {
    result = Ok({'Forward': 'yes', 'Back': 'no'});
  } else {
    result = Err(ArgumentError('Bad name'));
  }
  return result;
}
6
likes
0
pub points
15%
popularity

Publisher

unverified uploader

The Result<T> type implemented in Ok<T> and Err<T> types with unwrap methods.

Homepage

License

unknown (LICENSE)

More

Packages that depend on rust_like_result