匹配错误或空结果

时间:2017-05-21 10:37:23

标签: error-handling rust pattern-matching

我有一个函数返回Result<Vec<&str>, String>的节点列表。我的目的是检查错误或空向量以提前返回,或者如果有列表则继续。

这是我正在尝试的,除其他外,但编译器抱怨x的类型。

let nodes = list_nodes(client, &service);
match nodes {
    Err(e) => {
        println!("Unable to list nodes: {:?}", e);
        return;
    },
    Ok(x) if x.as_slice() == []  => {
        println!("No nodes found for service: {}", service);
        return;
    }
    _ => {}
}

错误是:

error[E0282]: type annotations needed
  --> src/main.rs:28:18
   |
28 |         Ok(x) if x.as_slice() == []  => {
   |                  ^^^^^^^^^^^^^^^^^^ cannot infer type for `A`

1 个答案:

答案 0 :(得分:2)

问题实际上是它无法推断出[]的类型。类型检查器不能假设此处的[]x.as_slice()具有相同的类型,因为PartialEq特征(其中==来自)允许右侧的实例左边的另一种类型。您可以通过查看切片的长度来轻松解决此问题,或使用is_empty()检查切片是否为空:

match nodes {
    Err(e) => {
        println!("Unable to list nodes: {:?}", e);
        return;
    },
    Ok(ref x) if x.as_slice().is_empty() => {
        println!("No nodes found for service: {}", service);
        return;
    }
    _ => {}
}

此外,引用x(与我上面已完成的ref x一样)可以防止您可能获得的其他错误,从而避免移动{{1}当它仍由x拥有时。