Get started with Rust

This document shows you how to set up a local Rust development environment, install one of the Cloud Client Libraries for Rust, and run your first Google Cloud API request.

Before you begin

Before running the commands in this document, complete the following prerequisites:

Create a Rust project

Complete the following steps to create a binary crate for your program:

  1. Create a binary crate:

    cargo new my-project
    
  2. Change to the new project directory:

    cd my-project
    

Install a Google Cloud client library

The Cloud Client Libraries for Rust provide idiomatic Rust clients for Google Cloud services such as Secret Manager. To add and build the Secret Manager client library, complete the following steps:

  1. Enable the Secret Manager API in your project:

    gcloud services enable secretmanager.googleapis.com
    
  2. Add the Secret Manager client library to your project:

    cargo add google-cloud-secretmanager-v1
    
  3. Add the google-cloud-gax crate for pagination helpers:

    cargo add google-cloud-gax
    
  4. Add the tokio crate for the asynchronous runtime:

    cargo add tokio --features macros,rt-multi-thread
    
  5. Replace the contents of src/main.rs with the following code to list secrets in your project:

    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error>> {
        use google_cloud_gax::paginator::ItemPaginator as _;
        use google_cloud_secretmanager_v1::client::SecretManagerService;
        let project_id = std::env::args().nth(1).unwrap();
        let client = SecretManagerService::builder().build().await?;
    
        let mut items = client
            .list_secrets()
            .set_parent(format!("projects/{project_id}"))
            .by_item();
        while let Some(item) = items.next().await {
            println!("{}", item?.name);
        }
        Ok(())
    }

  6. Build your program to verify that it compiles without errors:

    cargo build
    

Run your Rust program

Authenticate your local environment and run the sample program:

  1. Configure Application Default Credentials for your local environment:

    gcloud auth application-default login
    
  2. Run your program, passing your Google Cloud project ID as an argument:

    PROJECT_ID=$(gcloud config get project)
    cargo run -- "${PROJECT_ID}"
    

    The program prints the names of the secrets in your project. If your project doesn't have any secrets yet, create a secret and run the command again to see it in the output.

Clean up

To avoid incurring charges to your Google Cloud account for the resources used in this document, delete any test secrets that you created and remove the local my-project directory when you're finished.