← Rust EspañolChapter 04 of 13

Funciones

## Objetivos de Aprendizaje - Definir y llamar funciones - Usar parametros y valores de retorno - Dominar la sintaxis de metodos - Comprender la coincidencia de patrones con match ## Fundamentos de Funciones ### Declaracion ```rust fn function_name() { // cuerpo de la funcion } ``` ### Llamar Funciones ```rust fn main() { greet(); greet(); } fn greet() { println!("Hello!"); } ``` ## Parametros ### Un Parametro ```rust fn print_number(n: i32) { println!("Number: {}", n); } fn main() { print_number(42); } ``` ### Multiples Parametros ```rust fn add(a: i32, b: i32) { println!("{} + {} = {}", a, b, a + b); } fn main() { add(5, 3); } ``` ### Nomenclatura de Parametros ```rust fn greet(name: &str, age: u32) { println!("Hello {}, you are {} years old", name, age); } fn main() { greet("Alice", 30); } ``` ## Valores de Retorno ### Retorno Implicito ```rust fn add(a: i32, b: i32) -> i32 { a + b // Sin punto y coma = valor de retorno } fn main() { let sum = add(5, 3); println!("{}", sum); // Imprime: 8 } ``` ### Retorno Explicito ```rust fn add(a: i32, b: i32) -> i32 { return a + b; // Retorno explicito (menos comun) } ``` ### Retorno Anticipado ```rust fn absolute_value(n: i32) -> i32 { if n < 0 { return -n; // Retorno anticipado } n // Retorno normal } ``` ### Sin Valor de Retorno ```rust fn greet(name: &str) { println!("Hello, {}!", name); // Sin tipo de retorno -> significa () (tipo unidad) } fn main() { let result = greet("Alice"); // result es () } ``` ## Sintaxis de Metodos Los metodos son funciones asociadas a un tipo: ```rust struct Rectangle { width: u32, height: u32, } impl Rectangle { // &self es referencia a la instancia fn area(&self) -> u32 { self.width * self.height } // Metodo con parametros fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } // Metodo estatico (funcion asociada) fn new(width: u32, height: u32) -> Rectangle { Rectangle { width, height } } } fn main() { let rect = Rectangle::new(30, 50); println!("Area: {}", rect.area()); } ``` ## Funciones Asociadas Las funciones asociadas no toman `self` como parametro: ```rust impl Rectangle { fn square(size: u32) -> Rectangle { Rectangle { width: size, height: size } } } fn main() { let sq = Rectangle::square(10); } ``` ## Multiples Bloques impl ```rust impl Rectangle { fn area(&self) -> u32 { self.width * self.height } } impl Rectangle { fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } } ``` ## Coincidencia de Patrones con match ```rust fn main() { let x = 3; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), _ => println!("something else"), } } ``` ### match con Valores ```rust fn main() { let score = 85; let grade = match score { 90..=100 => "A", 80..=89 => "B", 70..=79 => "C", 60..=69 => "D", _ => "F", }; println!("Grade: {}", grade); // Grade: B } ``` ### match con Multiples Sentencias ```rust fn main() { let x = 1; match x { 1 => { let y = 2; println!("x = 1, y = {}", y); } 2 => println!("x = 2"), _ => println!("x is something else"), } } ``` ### match con Variables Vinculadas ```rust fn main() { let msg = Some(42); match msg { Some(n) => println!("Number: {}", n), None => println!("No number"), } } ``` ### Sintaxis if let ```rust fn main() { let msg = Some(42); // Abreviacion para patron unico if let Some(n) = msg { println!("Number: {}", n); } } ``` ### match con Enum ```rust enum Direction { North, South, East, West, } fn main() { let direction = Direction::North; match direction { Direction::North => println!("Heading north"), Direction::South => println!("Heading south"), Direction::East => println!("Heading east"), Direction::West => println!("Heading west"), } } ``` ## Closures Los closures son funciones anonimas que capturan su entorno: ```rust fn main() { let add_one = |x| x + 1; println!("{}", add_one(5)); // 6 let add = |a, b| a + b; println!("{}", add(2, 3)); // 5 // Anotaciones de tipo let square = |x: i32| -> i32 { x * x }; println!("{}", square(4)); // 16 } ``` ### Closures Capturando el Entorno ```rust fn main() { let x = 10; // El closure captura x del entorno let closure = || x + 5; println!("{}", closure()); // 15 } ``` ## Funciones de Orden Superior ```rust fn apply(x: i32, f: F) -> i32 where F: Fn(i32) -> i32, { f(x) } fn main() { let result = apply(5, |x| x * 2); println!("{}", result); // 10 } fn twice(f: F) -> impl Fn(i32) -> i32 where F: Fn(i32) -> i32, { move |x| f(f(x)) } ``` ## Resumen - Las funciones se declaran con la palabra clave `fn` - Los parametros necesitan anotaciones de tipo - El tipo de retorno se especifica con `->` - La ultima expresion se devuelve implicitamente (sin punto y coma) - Los metodos se definen en bloques `impl` con `&self` - `match` es coincidencia de patrones exhaustiva - `if let` para coincidencia de patron unico - Los closures son funciones anonimas que capturan el entorno

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →