考虑以下代码,使用and_then
将两个方法链接在一起,返回包含为Result
的输出:
use std::net::TcpListener;
fn main() {
match TcpListener::bind("127.0.0.1:2000").and_then(|s| s.accept()) {
Ok((stream, addr)) => ...,
Err(e) => ...,
}
}
是否有更优雅的方式将bind
和accept
联系在一起?这似乎是一种常见的模式。 我希望 ?
可以提供帮助:
match TcpListener::bind("127.0.0.1:2000")?.accept()
但这不会编译:
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`
(我正在运行rustc 1.20.0 (f3d6973f4 2017-08-27)
。)
编辑:?
似乎没有我想到的语义,这也解释了错误,请参阅1(谢谢,@ Joe Clay)。我正在寻找与and_then
相同的行为,但语法更优雅。