Cloud Storage is a managed service for storing unstructured data. The
google-cloud-storage crate in the Cloud Client Libraries for Rust provides an
idiomatic Rust API that resumes interrupted uploads and downloads, verifies
data integrity, retries transient metadata errors, and polls long-running
operations.
This document shows you how to create a Cloud Storage bucket, write an object to that bucket, read the object contents back, and delete both resources.
Before you begin
Before running the code in this document, complete the following prerequisites:
- Create or select a Google Cloud project with billing enabled.
- Follow Get started with Rust to install Rust and set up your development environment.
- Configure Application Default Credentials and grant your principal an
Identity and Access Management (IAM) role with permission to create and delete buckets
and objects, such as Storage Admin (
roles/storage.admin).
Dependencies
Add the Cloud Storage client library and supporting crates to your
Cargo.toml file:
cargo add google-cloud-storage anyhow bytes
cargo add tokio --features macros,rt-multi-thread
Create a bucket
Operations on buckets and object metadata use the StorageControl client:
Initialize a
StorageControlclient:Configure a
create_bucketrequest with your project ID and globally unique bucket ID:Optional: Configure bucket attributes such as uniform bucket-level access:
Send the request and await the created
Bucketmetadata:
Write an object
Operations that read or write object data use the Storage client:
Initialize a
Storageclient:Write an object named
hello.txtto the bucket usingwrite_object:
Read an object
To read the contents of an object, call read_object and collect the streamed
chunks:
When executed, this step prints the downloaded bytes:
object contents successfully downloaded b"Hello World!"
Delete the object and bucket
Delete the object and bucket in your program when they are no longer needed:
Complete code
The following function combines all of the preceding steps:
Clean up
If the sample exits early before running the deletion steps, delete the bucket manually so that you don't incur ongoing charges for the resources created in this document.