Sign In
Frontend & Clients

Rust

The Rivet Rust client provides a way to connect to and interact with actors from Rust applications.


Quickstart

Create a new Rust project

Create a new Rust project:

Command Line
cargo new my-app
cd my-app

Add dependencies

Add Rivet client & related dependencies to your project:

Command Line
cargo add rivetkit-client
cargo add serde_json
cargo add tokio --features full

Define your actor schema and implementation. Create a new file for your actor:

// actors/counter.ts
import { Actor } from '@rivetkit/actor';

export interface CounterState {
  count: number;
}

export class CounterActor extends Actor<CounterState> {
  getInitialState() {
    return { count: 0 };
  }

  increment() {
    this.setState({ count: this.state.count + 1 });
  }

  decrement() {
    this.setState({ count: this.state.count - 1 });
  }
}

Create your client

Modify src/main.rs to connect to your actor:

use rivetkit_client::{Client, EncodingKind, GetOrCreateOptions, TransportKind};
use serde_json::json;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Replace with your endpoint URL after deployment
    let client = Client::new(
        "http://localhost:8080",
        TransportKind::Sse,
        EncodingKind::Json
    );
    
    // Get or create an actor instance
    let options = GetOrCreateOptions::default();
    let counter = client.get("counter", [].into(), options)?
      .connect();
    
    // Subscribe to events
    counter.on_event("newCount", |args| {
        let count = args[0].as_i64().unwrap();
        println!("Event: {}", count);
    }).await;
    
    // Call an action
    let result = counter.action("increment", vec![json!(5)]).await?;
    println!("Action: {}", result);
    
    // Wait to receive events
    tokio::time::sleep(Duration::from_secs(1)).await;
    
    Ok(())
}

Start the Rivet development studio to test your actors locally:

npx rivetkit dev

This will start the local development server and open the Rivet Studio in your browser where you can interact with your actors.

Run your client

In a separate terminal, run your client code:

Command Line
cargo run

You should see output like:

C++
Event: 5 Action: 5

Run it again to see the state update.

Deploy your actors to production:

npx rivetkit deploy

This will build and deploy your actors to the Rivet cloud platform. Make sure you're logged in with rivetkit login.

Next Steps

Suggest changes to this page