Consider the following code that uses and_then
to chain together two methods returning outputs wrapped up as Result
s:
use std::net::TcpListener;
fn main() {
match TcpListener::bind("127.0.0.1:2000").and_then(|s| s.accept()) {
Ok((stream, addr)) => ...,
Err(e) => ...,
}
}
Is there a more elegant way to chain together bind
and accept
? This seems like a common pattern. I was hoping that maybe ?
could help:
match TcpListener::bind("127.0.0.1:2000")?.accept()
But this won't compile:
error[E0277]: the trait bound `(): std::ops::Try` is not satisfied
--> src/main.rs:21:11
|
21 | match TcpListener::bind(socket)?.accept() {
| --------------------------
| |
| the `?` operator can only be used in a function that returns `Result` (or another type that implements `std::ops::Try`)
| in this macro invocation
|
= help: the trait `std::ops::Try` is not implemented for `()`
= note: required by `std::ops::Try::from_error`
(I'm running rustc 1.20.0 (f3d6973f4 2017-08-27)
.)
EDIT: ?
does not seem to have the semantics I have in mind, which also explains the error, see 1 (thanks, @Joe Clay). I am looking for the same behavior I get with and_then
, but with a more elegant syntax.