Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 39 ยท Architecture and Setup

Rust Basics You Need for Tauri

The Rust you need to write Tauri commands: variables, ownership and borrowing, structs, enums, Result and Option, the ? operator and derive macros like Serialize.

You do not need to master Rust to build Tauri apps. A few concepts cover most command code: values and borrowing, structs and enums, Result and Option, and derive macros. This lesson teaches exactly those, with runnable examples that use only Rust's standard library. For the full language, see the Rust tutorial.

Variables and types

Variables are immutable by default. Add mut to change them. Types are usually inferred.

Rust
let name = "Ada";        // &str, text borrowed from the program
let mut count = 0;       // i32, can change
count += 1;
let owned = String::from("Ada"); // String, text you own and can grow

Two string types confuse beginners. &str is a read-only view of text; String owns its characters. Command arguments are often &str when you only read them, and String when you need to keep or return them.

Ownership and borrowing

Every value has one owner. When the owner goes out of scope, the value is freed. You can pass a value by move (the new owner takes it) or by reference (borrow it).

Rust
fn shout(text: &str) -> String {   // borrows text, returns a new owned String
    text.to_uppercase()
}

Rules to remember: any number of shared borrows (&T) or one mutable borrow (&mut T) at a time. This is what prevents data races, and it is why shared state across threads in Tauri needs a Mutex (see State management).

Rust Rust: borrowing versus moving

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Structs

A struct groups named fields. Methods go in an impl block.

Rust
struct Note {
    id: u32,
    title: String,
    pinned: bool,
}

impl Note {
    fn new(id: u32, title: &str) -> Self {
        Note { id, title: title.to_string(), pinned: false }
    }
}

In Tauri, structs describe the data you send to and from the frontend, and the shared application state.

Enums, Option and Result

Enums are types with a fixed set of variants, which can carry data.

Rust
enum Status {
    Draft,
    Published { url: String },
}

Two enums from the standard library appear in nearly every command:

  • Option<T> is either Some(value) or None. Rust has no null.
  • Result<T, E> is either Ok(value) or Err(error). A command that can fail returns a Result, and Tauri turns Err into a rejected Promise.
Rust Rust: Option, Result and match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The ? operator

Writing match on every Result gets noisy. The ? operator returns early with the error if there is one, otherwise unwraps the value:

Rust
fn parse_and_double(text: &str) -> Result<i32, std::num::ParseIntError> {
    let n: i32 = text.parse()?;   // on error, return Err right here
    Ok(n * 2)
}

This keeps command bodies short. The function's error type must be convertible from the error you propagate; that is why error enums often implement From.

Rust Rust: the ? operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Derive macros and serde

Tauri sends data as JSON, so your types need to convert to and from it. The serde crate does that. You opt in with derive:

Rust
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Debug)]
struct Note {
    id: u32,
    title: String,
    pinned: bool,
}
  • Serialize: Rust value to JSON. Needed for anything a command returns.
  • Deserialize: JSON to Rust value. Needed for anything a command receives as a struct.
  • Clone, Debug: handy copies and printing.

Field names become JSON keys. Use #[serde(rename_all = "camelCase")] on a struct to match JavaScript naming.

The standard library alone cannot run serde, so the Rust examples here avoid it; the idea carries over directly.

Modules and use

Code lives in modules. Split big lib.rs files into mod notes; (a file notes.rs), and use pub to expose items. You import with use, for instance use tauri::State;.

Closures and move

Tauri callbacks, such as menu handlers and event listeners, are closures. When a closure needs to use a variable after the surrounding function ends, you write move:

Rust
let handle = app.handle().clone();
app.on_menu_event(move |_app, event| {
    println!("{} clicked, using handle {:?}", event.id().0, handle.package_info().name);
});

move transfers the captured variables into the closure so they live as long as the closure does.

Reading compiler errors

Rust's compiler is verbose on purpose. Read the first error, read its help: note and the highlighted line. Errors about "borrowed value does not live long enough" or "cannot move out of" nearly always mean: clone the value, borrow it, or restructure ownership.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a command do when it returns Err(...) in Tauri?

    Tauri serializes the error and rejects the JavaScript Promise.
  2. 2. What is the difference between &str and String?

    Ownership is the distinction: String owns heap text, &str just borrows it.
  3. 3. What does the ? operator do?

    It propagates errors up the call chain with minimal code.
  4. 4. Which derive is needed for a struct that a command returns to JavaScript?

    Returned values must serialize to JSON; received struct arguments need Deserialize.

Summary

  • Immutable by default; mut opts in to change.
  • Ownership and borrowing keep memory safe; share across threads with a Mutex.
  • Structs hold data, enums model alternatives; Option and Result replace null and exceptions.
  • ? propagates errors; Serialize and Deserialize connect Rust types to JSON.
  • Closures with move power callbacks.

Next: State management in Rust