嵌套匹配在惯用的 Rust 中是一种不好的做法吗? [英] Are nested matches a bad practice in idiomatic Rust?
问题描述
我有一个 get_url_content
函数并且不关心错误(这只是一个测试).它返回一个 Option
.
I have a get_url_content
function and don't care about errors (it's just a test). It returns an Option<String>
.
extern crate hyper;
use std::io::Read;
use hyper::client::Client;
fn get_url_content(url: &str) -> Option<String> {
let client = Client::new();
let mut s = String::new();
match client.get(url).send() {
Ok(mut res) => {
match res.read_to_string(&mut s) {
Ok(_) => {
Some(s)
},
Err(_) => {
None
}
}
},
Err(_) => {
None
}
}
}
此功能运行良好,但我发现它不容易阅读.我认为有一些关于这种情况的最佳实践可以使其更具可读性.嵌套匹配是否是一种不好的做法(如 JS 中的回调地狱),如果是,如何避免?
This function works fine but I find it's not easy to read. I think there are some best practices about this kind of case to make it more readable. Are nested matches a bad practice (like callback hell in JS) and if so, how to avoid it?
推荐答案
让事情更简洁的最简单方法是去掉一些大括号:
The easiest way to make things a bit cleaner is to drop some braces:
match client.get(url).send() {
Ok(mut res) =>
match res.read_to_string(&mut s) {
Ok(_) => Some(s),
Err(_) => None,
},
Err(_) => None,
}
内部匹配可以更简洁地表达为
The inner match can be expressed a little cleaner perhaps as
match client.get(url).send() {
Ok(mut res) =>
res.read_to_string(&mut s).ok().map(|_| s),
Err(_) => None,
}
这建议在外部类型上使用 map
(以获得 Result
),然后使用 .unwrap_or 删除结果(无)
或 .unwrap_or_default()
This suggests using a map
on the outer type (to get Result<Option<_>, _>
) and then dropping the result with .unwrap_or(None)
or .unwrap_or_default()
client.get(url).send()
.map(|mut res| res.read_to_string(&mut s).ok().map(|_| s))
.unwrap_or(None)
这篇关于嵌套匹配在惯用的 Rust 中是一种不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!