我如何从表达式中“返回”?

时间:2019-01-02 14:23:34

标签: rust

此功能运行良好:找到适配器后,它将停止并返回。

fn choose_adapter(instance: vk::Instance) -> Option<Adapter<vk::Backend>> {
    let adapters = instance.enumerate_adapters();

    for adapter in adapters {
        if adapter.info.device_type == DeviceType::DiscreteGpu {
            return Some(adapter);
        }
    }
    return None;
}

以下修改无法编译。将;添加到Some(adapter)会使它失效,并且始终评估为None

let adapter = match {
    let adapters = instance.enumerate_adapters();

    for adapter in adapters {
        if adapter.info.device_type == DeviceType::DiscreteGpu {
            Some(adapter)
        }
    }
    None
} {
    Some(val) => val,
    None => panic!(""),
};

如何使后一个表达式像函数一样工作?

1 个答案:

答案 0 :(得分:3)

您可能想要

let adapter = instance
    .enumerate_adapters()
    .into_iter()
    .find(|adapter| adapter.info.device_type == DeviceType::DiscreteGpu)
    .expect("no discrete GPU adapter found");

对于您的实际问题,如果要在不从函数返回的情况下提前退出for循环,则需要使用break

let adapter = {
    let adapters = instance.enumerate_adapters();
    let mut found = None;
    for adapter in adapters {
        if adapter.info.device_type == DeviceType::DiscreteGpu {           
            found = Some(adapter);
            break;
        }
    }
    found
};