0

In Rust, is it possible to chain more functions after ok, unwrap or expect?

Given code:

stdin()
    .read_line(&mut guess)
    .ok()
    .expect("Couldn't read line!");

If I want to trim the string, is there a syntax like this?

stdin()
    .read_line(&mut guess)
    .ok().trim()
    .expect("Couldn't read line!");

I know using match I could do it https://stackoverflow.com/a/56264723/15504324

lijeles952
  • 265
  • 1
  • 8

1 Answers1

0

In this case the problem is that, you cannot, because the buffer is guess, readline would return the bytes read

Anyway:

You can use map to operate the value in case there is any Before unwraping/expecting:

Ok("Foo bar ")
    .ok()
    .map(str::trim)
    .expect("Couldn't read line!");

After it you can use the type already, so just chain the call.

Ok("Foo bar ")
    .unwrap()
    .trim();
Netwave
  • 40,134
  • 6
  • 50
  • 93