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:
Handle unknown values
When an enum receives an unrecognized string value, .value() returns None,
while .name() and JSON serialization continue to work as expected:
For unknown integer values, JSON serialization also continues to work as
expected, while .value() returns the integer and .name() returns None:
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:
When writing a match expression over a non-exhaustive enum, include the
wildcard pattern (_) to maintain backward compatibility
when a service adds new variants:
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:
You can also consider the unstable
non_exhaustive_omitted_patterns lint.