rust_like_result 2.1.0 copy "rust_like_result: ^2.1.0" to clipboard
rust_like_result: ^2.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 {
  
  // Ok:
  Result<Map> res = Ok({'Forward': 'yes', 'Back': 'no'});
  print(res); // Ok({Forward: yes, Back: no})
  print(res is Ok ? 'Ok' : 'Err'); // Ok
  print(res.unwrap); // {Forward: yes, Back: no}
  print(res.unwrapOrDefault({})); // {Forward: yes, Back: no}
  print(res.unwrapOrElse( (e) => {'error':e} )); // {Forward: yes, Back: no}
  

  // Err:
  res = Err(ArgumentError('Bad name'));
  print(res); // Err(Invalid argument(s): Bad name)
  print(res is Ok ? 'Ok' : 'Err'); // Err
  // print(res.unwrap); // raises exception 'Invalid argument(s): Bad name'
  print(res.unwrapOrDefault({})); // {}
  print(res.unwrapOrElse( (e) => {'Got error':e} )); // {Got error: Invalid argument(s): Bad name}


  // tryAsResult...() - calls function and return result as Ok, or Err if exception was raised:
  Result ok = await tryAsResultAsync( () => File('notExistsFile').rename('newPath')); 
  print(ok); // Err(Bad state: FileSystemException: Cannot rename ...
  
  ok = await tryAsResultAsync( () => Directory('.').list()); 
  print(ok); // Ok(Instance of '_ControllerStream<FileSystemEntity>')
  
  ok = tryAsResultSync(() => File('notExistsFile').renameSync('newPath'));
  print(ok); // Err(Bad state: FileSystemException ...
  
  ok = tryAsResultSync(() => Directory('.').listSync());
  print(ok); // Ok([File:...

  // Pipe operator stays Err as is, but calls right-side function on val of the left-side Ok.
  var r = Err<int>(ArgumentError('Lalala')) | (((x)=>x*2) as dynamic Function(int?));
  print(r); // Err(Invalid argument(s): Lalala)

  r = Ok(123) | (((x)=>x*2) as dynamic Function(int?));
  print(r); // Ok(246)


}
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