Working with enums

This document explains how to use enumerations (enums) in the Cloud Client Libraries for Rust, including handling enum values introduced after the library release.

Background

Google Cloud services use enumerations for fields that accept or provide a discrete, limited set of values. Although the allowed values are known at any point in time, services can add new values over time.

The Cloud Client Libraries for Rust can send and receive enum values, including values introduced after the library was released.

Before you begin

The examples in this document run locally and don't call Google Cloud services, so you don't need a Google Cloud project or account. The examples use the Secret Manager client library, and the same principles apply to enumerations in any other client library.

Dependencies

Add the Secret Manager client library and supporting crates to your Cargo.toml file:

cargo add google-cloud-secretmanager-v1 serde_json anyhow

Handle known values

When working with known values, you can construct enum variants directly or convert them from integer or string representations:

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)?);

Handle unknown values

When an enum receives an unrecognized string value, .value() returns None, while .name() and JSON serialization continue to work as expected:

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);

For unknown integer values, JSON serialization also continues to work as expected, while .value() returns the integer and .name() returns 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);

Prepare for upgrades

Enums in the Cloud Client Libraries for Rust can gain new variants in future releases. To avoid breaking your application when a service adds new variants, the library marks generated enums as #[non_exhaustive].

Assume the State enum is imported into scope:

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

When writing a match expression over a non-exhaustive enum, include the wildcard pattern (_) to maintain backward compatibility when a service adds new variants:

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(())
}

If you want a linter warning when new variants appear so you can review and update your match arms, enable the 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(())
}

You can also consider the unstable non_exhaustive_omitted_patterns lint.