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

outdated

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

example/example.dart

import 'dart:io';

import 'package:rust_like_result/rust_like_result.dart';

void main() async {
  // 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');

  Result ok = await tryAsResultAsync( () => File('notExistsFile').rename('newPath')); 
  print(ok); // Err
  ok = await tryAsResultAsync( () => Directory('.').list()); 
  print(ok); // Ok
  ok = tryAsResultSync(() => File('notExistsFile').renameSync('newPath'));
  print(ok); // Err
  ok = tryAsResultSync(() => Directory('.').listSync());
  print(ok); // Ok

}

/// 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
0%
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