Hoja de trucos de Rust

Guía rápida de Rust y fundamentos para desarrollo seguro y robusto. Q2BSTUDIO ofrece software a medida, IA, ciberseguridad y servicios cloud AWS/Azure.

23 sept 2025 • 4 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Hoja de trucos de Rust y servicios de Q2BSTUDIO Bienvenido a una guía rápida de Rust pensada para desarrolladores y equipos que necesitan crear software robusto y seguro. En Q2BSTUDIO, empresa de desarrollo de software y aplicaciones a medida, ofrecemos soluciones que combinan programación eficiente con servicios avanzados como inteligencia artificial, ciberseguridad y servicios cloud aws y azure. Si buscas crear una aplicación a medida o un producto de software a medida, podemos ayudarte desde el diseño hasta la puesta en producción, incluyendo integración con servicios cloud como AWS y Azure y soluciones de business intelligence con Power BI. Consulta nuestras opciones de desarrollo en Desarrollo de aplicaciones y software a medida o explora nuestros servicios cloud en Servicios cloud AWS y Azure.

1. INSTALACIÓN Comandos básicos para preparar el entorno Rust: curl --proto =https --tlsv1 1.2 -sSf https://sh.rustup.rs | sh para instalar rustup, rustc --version para comprobar la versión, cargo new mi_proyecto y cd mi_proyecto para crear y entrar en un proyecto, cargo build para compilar y cargo run para ejecutar.

2. CONCEPTOS BÁSICOS Ejemplo mínimo: fn main() { println!(Hola mundo!); // imprimir let x = 5; // variable inmutable let mut y = 10; // variable mutable const PI: f64 = 3.1415; // constante }

3. TIPOS DE DATOS Tipos escalares: let a: i32 = -42; let b: u32 = 42; let c: f64 = 3.14; let d: bool = true; let e: char = R; Tipos compuestos: let tup: (i32, f64, char) = (500, 6.4, z); let (x, y, z) = tup; let arr = [1, 2, 3, 4, 5]; let slice: &[i32] = &arr[1..3];

4. FLUJO DE CONTROL if x > 5 { println!(Greater!); } else { println!(Smaller!); } Bucle for: for n in 1..5 { println!({}, n); } Bucle while: let mut contador = 0; while contador < 3 { println!(count = {}, contador); contador += 1; }

5. FUNCIONES Declaración y retorno implícito: fn add(a: i32, b: i32) -> i32 { a + b } fn main() { println!({}, add(5, 3)); }

6. PROPIEDAD Y PRÉSTAMO Movimientos y referencias: fn main() { let s = String::from(Hello); takes_ownership(s); // s se mueve let x = 5; makes_copy(x); // i32 implementa Copy println!({}, x); // x sigue siendo válido let s2 = String::from(Hi); borrow(&s2); println!({}, s2); } fn takes_ownership(s: String) { println!({}, s); } fn makes_copy(x: i32) { println!({}, x); } fn borrow(s: &String) { println!({}, s); }

7. ESTRUCTURAS Y ENUMERACIONES struct User { name: String, age: u8 } enum Direction { Up, Down, Left, Right } Uso: let user = User { name: String::from(Alice), age: 25 }; println!({}, user.name); let dir = Direction::Left; match dir { Direction::Up => println!(Up), Direction::Down => println!(Down), Direction::Left => println!(Left), Direction::Right => println!(Right) }

8. TRAITS E IMPLEMENTACIONES trait Greet { fn say_hello(&self); } struct Person { name: String } impl Greet for Person { fn say_hello(&self) { println!(Hello, {}, self.name); } } fn main() { let p = Person { name: String::from(Bob) }; p.say_hello(); }

9. MANEJO DE ERRORES Ejemplo con Result y manejo con match: fn divide(a: f64, b: f64) -> Result<f64, String> { if b == 0.0 { Err(String::from(Division by zero!)) } else { Ok(a / b) } } fn main() { match divide(10.0, 2.0) { Ok(res) => println!(Result: {}, res), Err(err) => println!(Error: {}, err) } }

10. COLECCIONES Vectores: let mut v = vec![1, 2, 3]; v.push(4); for i in &v { println!({}, i); } HashMap: use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(Alice, 10); scores.insert(Bob, 20); println!({:?}, scores);

11. MACROS COMUNES println!(Hello {}, Rust); dbg!(42); vec![1, 2, 3]; Estas macros facilitan depuración y formateo.

12. LIFETIMES Y ALCANCE BÁSICO En Rust las referencias tienen tiempos de vida que garantizan seguridad en memoria. En funciones que devuelven referencias hay que asegurar que la referencia devuelta no viva más que los datos referenciados. Este concepto es clave cuando se trabaja con estructuras complejas o APIs que manejan datos prestados.

13. COMANDOS DE CARGO cargo new nombre_proyecto para crear un proyecto, cargo build para compilar, cargo run para ejecutar, cargo check para comprobar errores sin compilar, cargo test para pruebas, cargo fmt para formatear código y cargo doc --open para generar documentación.

Q2BSTUDIO Si tu equipo necesita apoyo para llevar proyectos en Rust a producción, integrar modelos de inteligencia artificial, desplegar en arquitecturas cloud o mejorar la ciberseguridad de tus aplicaciones, en Q2BSTUDIO ofrecemos servicios completos de desarrollo de software a medida, inteligencia artificial para empresas, agentes IA, automatización de procesos y servicios de inteligencia de negocio con Power BI. Contáctanos para diseñar soluciones adaptadas a tu negocio que combinan know how en desarrollo con seguridad y escalabilidad.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat