使用列舉

本文說明如何在 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。