Logo vun Rust Development

Rust Development

Organisatioun
navikt
rust-development

Idiomatisk Rust-utvikling med cargo, clippy, error handling, async/tokio, unsafe og testing

Iwwersiicht

Editeurnavikt
Repositorycopilot
Skill-Nummrust-development
Stären
60
Forks
16
Matgeliwwert Fichieren
1
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • 1 matgeliwwert Dateien

    Skripten, Virlagen a Referenzen, déi de Modell beim Schaffe liese kann. D'Dateie kënnen nëmme gelies ginn a ginn ni ausgeféiert.

  • Open Source

    Vum navikt op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Rust Development an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/navikt/copilot/tree/main/skills/rust-development
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/navikt/copilot.git /tmp/copilot
mkdir -p .claude/skills
cp -r /tmp/copilot/skills/rust-development .claude/skills/rust-development
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Rust Development an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Rust Development automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Rust Development net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

Rust Development Skill

Patterns, templates, and procedures for building high-quality Rust applications and libraries. Based on Microsoft Pragmatic Rust Guidelines and Rust API Guidelines.

When to Use

  • Setting up a new Rust project or workspace
  • Configuring Cargo.toml with recommended lints and dependencies
  • Implementing error handling (library vs application)
  • Writing async code with tokio
  • Reviewing or writing unsafe code
  • Optimizing performance with benchmarks
  • Structuring a crate for public API quality

Procedure: New Project Setup

1. Initialize

bash
cargo init <project-name>
cd <project-name>

2. Configure Cargo.toml

toml
[package]
name = "my-service"
version = "0.1.0"
edition = "2024"
rust-version = "1.85"

[dependencies]
anyhow = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }

[dev-dependencies]
proptest = "1"

[lints.rust]
missing_debug_implementations = "warn"
redundant_imports = "warn"
trivial_numeric_casts = "warn"
unsafe_op_in_unsafe_fn = "warn"
unused_lifetimes = "warn"

[lints.clippy]
cargo = { level = "warn", priority = -1 }
complexity = { level = "warn", priority = -1 }
correctness = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -1 }
perf = { level = "warn", priority = -1 }
style = { level = "warn", priority = -1 }
suspicious = { level = "warn", priority = -1 }
undocumented_unsafe_blocks = "warn"
clone_on_ref_ptr = "warn"
map_err_ignore = "warn"

3. Configure rustfmt

Create rustfmt.toml:

toml
edition = "2024"
max_width = 100
use_field_init_shorthand = true

4. Set up CI checks

Minimum verification pipeline:

bash
cargo fmt --check
cargo clippy -- -W clippy::pedantic
cargo test
cargo doc --no-deps
cargo audit

Procedure: Error Handling

Library Errors (thiserror)

Use struct-based errors with backtrace support per Microsoft guidelines:

rust
use std::backtrace::Backtrace;

#[derive(Debug)]
pub struct ParseError {
    kind: ParseErrorKind,
    backtrace: Backtrace,
}

#[derive(Debug, thiserror::Error)]
enum ParseErrorKind {
    #[error("invalid header: {0}")]
    InvalidHeader(String),
    #[error("missing field: {field}")]
    MissingField { field: &'static str },
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.kind.fmt(f)
    }
}

impl std::error::Error for ParseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.kind.source()
    }
}

Application Errors (anyhow)

rust
use anyhow::{Context, Result};

fn load_config(path: &str) -> Result<Config> {
    let content = std::fs::read_to_string(path)
        .context("failed to read config file")?;
    let config: Config = serde_json::from_str(&content)
        .context("failed to parse config")?;
    Ok(config)
}

Rule: Libraries expose structured errors. Applications use anyhow::Result.

Procedure: Async Application (tokio + axum)

Minimal HTTP service

rust
use axum::{Router, routing::get};
use tokio::net::TcpListener;
use tracing_subscriber::EnvFilter;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .json()
        .init();

    let app = Router::new()
        .route("/isalive", get(|| async { "Alive" }))
        .route("/isready", get(|| async { "Ready" }));

    let listener = TcpListener::bind("0.0.0.0:8080").await?;
    tracing::info!("listening on {}", listener.local_addr()?);
    axum::serve(listener, app).await?;
    Ok(())
}

Graceful shutdown

rust
use tokio::signal;

async fn shutdown_signal() {
    let ctrl_c = async {
        signal::ctrl_c().await.expect("failed to listen for ctrl+c");
    };

    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("failed to install SIGTERM handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        () = ctrl_c => {},
        () = terminate => {},
    }
}

// Usage:
axum::serve(listener, app)
    .with_graceful_shutdown(shutdown_signal())
    .await?;

Shared state

rust
use std::sync::Arc;
use tokio::sync::RwLock;

#[derive(Clone)]
struct AppState {
    db: sqlx::PgPool,
    cache: Arc<RwLock<HashMap<String, CachedItem>>>,
}

let state = AppState {
    db: sqlx::PgPool::connect(&database_url).await?,
    cache: Arc::new(RwLock::new(HashMap::new())),
};

let app = Router::new()
    .route("/items", get(list_items))
    .with_state(state);

Procedure: Unsafe Code Review

When writing or reviewing unsafe:

  1. Justify — is it novel abstractions, performance (with benchmarks), or FFI?
  2. Document — every unsafe block has a // SAFETY: comment
  3. Minimize — smallest possible unsafe scope
  4. Test — run cargo +nightly miri test for UB detection
  5. Verify — no aliasing violations, no data races, all invariants upheld
rust
// ✅ Correct — documented and minimal
// SAFETY: We verified the pointer is non-null and properly aligned
// in the constructor. The data outlives this reference because
// it is held by the owning Arc<T>.
unsafe { &*self.ptr }

// ❌ Wrong — undocumented, overly broad
unsafe {
    // lots of code here making it impossible to audit
}

Procedure: Performance Optimization

1. Use mimalloc as global allocator

rust
use mimalloc::MiMalloc;

#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;

2. Benchmark with criterion

rust
// benches/parse.rs
use criterion::{criterion_group, criterion_main, Criterion};

fn bench_parsing(c: &mut Criterion) {
    let input = include_str!("../fixtures/large_input.json");
    c.bench_function("parse_json", |b| {
        b.iter(|| parse(criterion::black_box(input)));
    });
}

criterion_group!(benches, bench_parsing);
criterion_main!(benches);

Enable debug symbols for flamegraphs:

toml
[profile.bench]
debug = 1

3. Avoid common performance pitfalls

rust
// ✅ Pre-allocate with capacity
let mut buffer = Vec::with_capacity(estimated_size);

// ✅ Use write! instead of format! on hot paths
use std::fmt::Write;
let mut output = String::new();
write!(output, "count: {count}")?;

// ✅ Cow for conditional ownership
fn process(input: &str) -> Cow<'_, str> {
    if needs_transform(input) {
        Cow::Owned(transform(input))
    } else {
        Cow::Borrowed(input)
    }
}

Procedure: Structured Logging

rust
use tracing::{info, warn, instrument};

#[instrument(skip(db), fields(user_id = %user_id))]
async fn process_request(user_id: &str, db: &PgPool) -> Result<()> {
    info!(event = "request.processing.started");

    let result = db.fetch_one(query).await?;

    info!(
        event = "request.processing.completed",
        rows_affected = result.rows_affected(),
    );

    Ok(())
}

Naming: <component>.<operation>.<state> — e.g., db.query.completed, http.request.failed.

Procedure: Testing Patterns

Unit tests (in-module)

rust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_valid_input() {
        let result = parse("valid input");
        assert_eq!(result.unwrap(), expected);
    }
}

Table-driven tests

rust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn conversion_cases() {
        let cases = [
            ("input1", "expected1"),
            ("input2", "expected2"),
            ("input3", "expected3"),
        ];

        for (input, expected) in cases {
            assert_eq!(convert(input), expected, "failed for input: {input}");
        }
    }
}

Async tests (tokio)

rust
#[tokio::test]
async fn fetches_user() {
    let pool = setup_test_db().await;
    let user = get_user(&pool, "test-id").await.unwrap();
    assert_eq!(user.name, "Test User");
}

Property-based tests (proptest)

rust
use proptest::prelude::*;

proptest! {
    #[test]
    fn roundtrip_serialization(input in "\\PC*") {
        let serialized = serde_json::to_string(&input).unwrap();
        let deserialized: String = serde_json::from_str(&serialized).unwrap();
        prop_assert_eq!(input, deserialized);
    }
}

API Design Checklist

Based on Rust API Guidelines:

  • Eagerly implement Debug, Clone, Default, Eq, Hash where applicable
  • Public enums and structs use #[non_exhaustive]
  • Functions accept borrowed params (&str, impl AsRef<Path>) not owned
  • Getters: fn name(&self) not fn get_name(&self)
  • Conversions: as_ (cheap ref), to_ (expensive), into_ (consuming)
  • Constructors: new (default), with_* (configured), from_* (conversion)
  • Builder pattern for 4+ optional parameters
  • Newtype wrappers for domain types (struct UserId(u64))
  • No Arc/Box in public signatures unless necessary
  • Iterators implement Iterator, DoubleEndedIterator, ExactSizeIterator where possible

Documentation Standards

rust
/// Short one-sentence summary. (imperative mood)
///
/// Detailed explanation if needed. Include examples for
/// non-trivial public items.
///
/// # Errors
///
/// Returns `ParseError` if the input is not valid UTF-8.
///
/// # Panics
///
/// Panics if `index` is out of bounds.
///
/// # Examples
///
/// ```
/// use my_crate::parse;
/// let result = parse("hello")?;
/// assert_eq!(result.len(), 5);
/// # Ok::<(), my_crate::ParseError>(())
/// ```
pub fn parse(input: &str) -> Result<Parsed, ParseError> {
    // ...
}

Required doc sections for public items: summary, # Errors, # Panics, # Examples. Module docs: //! at the top of lib.rs and significant modules.

References

Matgeliwwert Fichieren

De Modell liest dës Dateie bei Bedarf, wärend de Skill gelueden ass. Si ginn als liesbar Dateie bereetgestallt a ginn ni ausgeféiert.

Heefeg gestallte Froen

Wat mécht de KI-Skill Rust Development?

Idiomatisk Rust-utvikling med cargo, clippy, error handling, async/tokio, unsafe og testing

Firwat Rust Development op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Rust Development besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Rust Development an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/navikt/copilot/tree/main/skills/rust-development an. TypingMind liest d'Datei SKILL.md, bündelt déi zougehéiereg Dateien an installéiert dat Ganzt als Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Rust Development benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Rust Development benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Rust Development domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Rust Development gratis?

Jo. De Skill gëtt vum navikt ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇