使用枚举

本文档介绍了如何在 Rust 版 Cloud 客户端库中使用枚举 (enum),包括处理库发布后引入的枚举值。

背景

Google Cloud 服务对接受或提供离散、有限值集的字段使用枚举。虽然允许的值在任何时间点都是已知的,但服务可以随着时间的推移添加新值。

Rust 版 Cloud 客户端库可以发送和接收枚举值,包括在库发布后引入的值。

准备工作

本文档中的示例在本地运行,不调用 Google Cloud服务,因此您不需要 Google Cloud 项目或账号。这些示例使用 Secret Manager 客户端库,并且相同的原则适用于任何其他客户端库中的枚举。

依赖项

将 Secret Manager 客户端库和支持 crate 添加到 Cargo.toml 文件中:

cargo add google-cloud-secretmanager-v1 serde_json anyhow

处理已知值

处理已知值时,您可以直接构造枚举变体,也可以从整数或字符串表示法转换它们:

use google_cloud_secretmanager_v1::model::secret_version::State;
let enabled = State::Enabled;
println!("State::Enabled = {enabled}");
assert_eq!(enabled.value(), Some(1));
assert_eq!(enabled.name(), Some("ENABLED"));

let state = State::from(1);
println!("state = {state}");
assert_eq!(state.value(), Some(1));
assert_eq!(state.name(), Some("ENABLED"));

let state = State::from("ENABLED");
println!("state = {state}");
assert_eq!(state.value(), Some(1));
assert_eq!(state.name(), Some("ENABLED"));
println!("json = {}", serde_json::to_value(&state)?);

处理未知值

当枚举收到无法识别的字符串值时,.value() 会返回 None,而 .name() 和 JSON 序列化会继续按预期运行:

use google_cloud_secretmanager_v1::model::secret_version::State;
use serde_json::json;
let state = State::from("STATE_NAME_FROM_THE_FUTURE");
println!("state = {state}");
assert_eq!(state.value(), None);
assert_eq!(state.name(), Some("STATE_NAME_FROM_THE_FUTURE"));
println!("json = {}", serde_json::to_value(&state)?);
let u = serde_json::from_value::<State>(json!("STATE_NAME_FROM_THE_FUTURE"))?;
assert_eq!(state, u);

对于未知整数值,JSON 序列化也会继续按预期运行,而 .value() 会返回整数,.name() 会返回 None:

use google_cloud_secretmanager_v1::model::secret_version::State;
use serde_json::json;
const MAGIC_INT_FROM_THE_FUTURE: i32 = 17;
let state = State::from(MAGIC_INT_FROM_THE_FUTURE);
println!("state = {state}");
assert_eq!(state.value(), Some(17));
assert_eq!(state.name(), None);
println!("json = {}", serde_json::to_value(&state)?);
let s2 = serde_json::from_value::<State>(json!(17))?;
assert_eq!(state, s2);

为升级做好准备

Rust 版 Cloud 客户端库中的枚举在未来版本中可能会获得新的变体。 为避免在服务添加新变体时破坏应用,该库会将生成的枚举标记为 #[non_exhaustive]。

假设 State 枚举已导入到作用域中:

use google_cloud_secretmanager_v1::model::secret_version::State;

在针对并非详尽无遗枚举编写 match 表达式时,请添加通配符模式 (_),以便在服务添加新变体时保持向后兼容性:

fn match_with_wildcard(state: State) -> anyhow::Result<()> {
    use anyhow::Error;
    match state {
        State::Unspecified => {
            return Err(Error::msg("the documentation says this is never used"));
        }
        State::Enabled => println!("the secret is enabled and can be accessed"),
        State::Disabled => {
            println!("the secret version is not accessible until it is enabled")
        }
        State::Destroyed => {
            println!("the secret is destroyed, the data is no longer accessible")
        }
        State::UnknownValue(u) => {
            println!("unknown State variant ({u:?}) time to update the library")
        }
        _ => return Err(Error::msg("unexpected value, update this code")),
    };
    Ok(())
}

如果您希望在新变体出现时收到 Linter 警告,以便查看和更新 match 分支,请启用 wildcard_enum_match_arm Clippy lint:

fn match_with_warnings(state: State) -> anyhow::Result<()> {
    use anyhow::Error;
    #[warn(clippy::wildcard_enum_match_arm)]
    match state {
        State::Unspecified => {
            return Err(Error::msg("the documentation says this is never used"));
        }
        State::Enabled => println!("the secret is enabled and can be accessed"),
        State::Disabled => {
            println!("the secret version is not accessible until it is enabled")
        }
        State::Destroyed => {
            println!("the secret is destroyed, the data is no longer accessible")
        }
        State::UnknownValue(u) => {
            println!("unknown State variant ({u:?}) time to update the library")
        }
        _ => {
            // *If* your CI includes treating clippy warnings as errors,
            // consider using `unreachable!()`.
            return Err(Error::msg("unexpected value, update this code"));
        }
    };
    Ok(())
}

您还可以考虑使用不稳定的 non_exhaustive_omitted_patterns lint。