• Start

Languages

/

Rust

/

Methods

init

The .init() method for the SurrealDB Rust SDK initializes a new unconnected instance.

The .init() method initializes a new unconnected instance of the client.
This is typically used to create a global, static instance of the client.

Method Syntax
Surreal::init()
use std::sync::LazyLock;
use surrealdb::engine::remote::ws::{Client, Ws};
use surrealdb::Surreal;

static DB: LazyLock<Surreal<Client>> = LazyLock::new(Surreal::init);

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    // Connect to the database
    DB.connect::<Ws>("127.0.0.1:8000").await?;
    Ok(())
}

`Surreal::init()` can also be used to create an instance of `Surreal`, allowing you to choose at runtime which way to connect.

use std::env;
use std::sync::LazyLock;
use surrealdb::engine::any::Any;
use surrealdb::Surreal;

static DB: LazyLock<Surreal<Any>> = LazyLock::new(Surreal::init);

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    // Choose an endpoint at runtime using the `DB_ENDPOINT` environment variable
    // or fallback to the memory engine.
    let endpoint = env::var("DB_ENDPOINT").unwrap_or_else(|_| "mem://".to_owned());
    DB.connect(endpoint).await?;
    Ok(())
}

Was this page helpful?