Saltar a contenido

Rust - Entorno de Desarrollo

Guía completa para configurar un entorno de desarrollo Rust para backend que permita a Claude Code trabajar eficazmente.

Requisitos del Sistema

Componente Versión Mínima Recomendada
Rust 1.75 Latest stable
Cargo 1.75 Latest
rustfmt Incluido Latest
clippy Incluido Latest

Instalación de Rust

Todos los sistemas (rustup)

# Instalar rustup (gestor oficial)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Windows: descargar rustup-init.exe
# https://win.rustup.rs/

# Configurar PATH (se añade automáticamente)
source $HOME/.cargo/env

# Verificar
rustc --version
cargo --version
rustup --version

# Actualizar
rustup update

# Instalar componentes adicionales
rustup component add rustfmt    # Formateo
rustup component add clippy     # Linter
rustup component add rust-analyzer  # LSP

Múltiples versiones

# Instalar versión específica
rustup install 1.75.0

# Usar versión por defecto
rustup default stable

# Usar versión en proyecto específico
rustup override set 1.75.0

Herramientas Esenciales

# cargo-watch - Hot reload
cargo install cargo-watch
cargo watch -x run

# cargo-edit - Gestión de dependencias
cargo install cargo-edit
cargo add serde
cargo rm serde
cargo upgrade

# cargo-expand - Ver macros expandidas
cargo install cargo-expand
cargo expand

# sqlx-cli - Migraciones SQL
cargo install sqlx-cli --features postgres
sqlx migrate add create_users
sqlx migrate run

# diesel_cli - ORM
cargo install diesel_cli --no-default-features --features postgres
diesel setup
diesel migration generate create_users

# cargo-audit - Auditoría de seguridad
cargo install cargo-audit
cargo audit

# cargo-nextest - Tests más rápidos
cargo install cargo-nextest
cargo nextest run

# sccache - Cache de compilación
cargo install sccache
export RUSTC_WRAPPER=sccache

IDE y Extensiones

Visual Studio Code (Recomendado)

# Extensión rust-analyzer (obligatoria)
code --install-extension rust-lang.rust-analyzer

# Extensiones adicionales
code --install-extension serayuzgur.crates        # Gestión de crates
code --install-extension tamasfe.even-better-toml # TOML
code --install-extension vadimcn.vscode-lldb      # Debugger
code --install-extension usernamehw.errorlens     # Errores inline

settings.json:

{
    "rust-analyzer.checkOnSave.command": "clippy",
    "rust-analyzer.cargo.features": "all",
    "editor.formatOnSave": true,
    "[rust]": {
        "editor.defaultFormatter": "rust-lang.rust-analyzer"
    }
}

Frameworks Web

Actix-web (Alto rendimiento)

cargo add actix-web actix-rt
use actix_web::{web, App, HttpServer, Responder};

async fn hello() -> impl Responder {
    "Hello, World!"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/", web::get().to(hello))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

Axum (Tokio ecosystem)

cargo add axum tokio -F tokio/full
use axum::{routing::get, Router};

async fn hello() -> &'static str {
    "Hello, World!"
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(hello));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Rocket

cargo add rocket

Bases de Datos

SQLx (Async, compile-time checked)

cargo add sqlx -F runtime-tokio,postgres,macros

# Configurar DATABASE_URL
export DATABASE_URL="postgres://user:pass@localhost/dbname"

# Crear migraciones
sqlx migrate add create_users

# Aplicar migraciones
sqlx migrate run

# Verificar queries en compile-time
sqlx prepare

Diesel (ORM síncrono)

cargo add diesel -F postgres

# Setup
diesel setup
diesel migration generate create_users
diesel migration run

SeaORM (Async ORM)

cargo add sea-orm -F runtime-tokio-rustls,sqlx-postgres

Configuración de Proyecto

Cargo.toml típico

[package]
name = "myapp"
version = "0.1.0"
edition = "2021"

[dependencies]
# Web framework
axum = "0.7"
tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.5", features = ["cors", "trace"] }

# Database
sqlx = { version = "0.7", features = ["runtime-tokio", "postgres", "macros"] }

# Serialization
serde = { version = "1", features = ["derive"] }
serde_json = "1"

# Configuration
config = "0.14"
dotenvy = "0.15"

# Logging
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

# Error handling
anyhow = "1"
thiserror = "1"

[dev-dependencies]
tokio-test = "0.4"

Estructura de proyecto

myapp/
├── src/
│   ├── main.rs
│   ├── lib.rs
│   ├── config.rs
│   ├── routes/
│   │   ├── mod.rs
│   │   └── users.rs
│   ├── handlers/
│   ├── models/
│   ├── db/
│   │   ├── mod.rs
│   │   └── pool.rs
│   └── error.rs
├── migrations/
│   └── 20240101_create_users.sql
├── tests/
│   └── integration_test.rs
├── Cargo.toml
├── Cargo.lock
├── .env
└── Dockerfile

Comandos que Claude Code Ejecutará

# Build y ejecución
cargo build
cargo build --release
cargo run
cargo watch -x run  # Hot reload

# Testing
cargo test
cargo test -- --nocapture
cargo nextest run

# Formateo y linting
cargo fmt
cargo fmt -- --check
cargo clippy
cargo clippy -- -D warnings

# Dependencias
cargo add <crate>
cargo remove <crate>
cargo update
cargo tree

# Migraciones (SQLx)
sqlx migrate add <name>
sqlx migrate run
sqlx prepare

# Documentación
cargo doc --open

# Auditoría
cargo audit

Docker para Rust

Dockerfile Multi-stage

# Build stage
FROM rust:1.75-alpine AS builder
RUN apk add --no-cache musl-dev

WORKDIR /app
COPY Cargo.toml Cargo.lock ./
RUN mkdir src && echo "fn main() {}" > src/main.rs
RUN cargo build --release
RUN rm -rf src

COPY src ./src
RUN touch src/main.rs
RUN cargo build --release

# Runtime stage
FROM alpine:3.19
RUN apk add --no-cache ca-certificates

COPY --from=builder /app/target/release/myapp /usr/local/bin/

RUN adduser -D appuser
USER appuser

EXPOSE 8080
CMD ["myapp"]

Verificación del Entorno

#!/bin/bash
echo "=== Verificación Entorno Rust ==="

echo -e "\n--- Rust ---"
rustc --version
cargo --version
rustup --version

echo -e "\n--- Componentes ---"
rustup component list --installed

echo -e "\n--- Herramientas Cargo ---"
cargo --list | head -20

echo -e "\n=== Verificación Completa ==="

Recursos