0Pricing
Learn Rust Coding · Lección

Escritura de código genérico en Rust

Aprenda a escribir funciones y estructuras de datos que funcionen con varios tipos, mejorando la reutilización del código sin sacrificar la seguridad de tipos.

Escritura de código genérico en Rust es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 1 de 3. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Learn Rust Coding, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Learn Rust Coding incluye 3 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why Write Generic Code?

Imagine you need a function that finds the largest item in a list. What if you need it for numbers, and then for characters, and then for custom objects?

Without generics, you'd write a separate function for each type, leading to lots of duplicated code. This is where generics come in!

Introducing Generics

Generics allow you to write code that works with multiple types, without repeating yourself. They are a way to write flexible and reusable functions or data structures.

Think of it as a blueprint that can be adapted for different materials.

Your First Generic Function

To make a function generic, we declare type parameters in angle brackets <> after the function name. A common type parameter name is T (for Type).

This print_anything function can now print any type!

fn print_anything<T>(item: T) {
    println!("The item is: {}", item);
}

pub fn main() {
    print_anything(5);
    print_anything("hello");
    print_anything(true);
}

Type Parameters Explained

The <T> in fn print_anything<T>(item: T) means T is a placeholder for a type. When you call the function with an i32, T becomes i32.

  • Type Parameters: Generic types are usually named with uppercase letters, like T, U, V.
  • Flexibility: The compiler figures out the concrete type at compile time.

Adding Behavior: Trait Bounds

Sometimes, your generic function needs its type parameter T to have specific behaviors. For example, if you want to compare two Ts, T must be comparable.

We add trait bounds to specify these requirements. Here, T: PartialOrd + Copy means T must implement the PartialOrd (partial ordering for comparison) and Copy traits.

fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut largest = list[0];
    for &item in list.iter() {
        if item > largest {
            largest = item;
        }
    }
    largest
}

pub fn main() {
    let number_list = vec![34, 50, 25, 100, 65];
    println!("Largest number: {}", largest(&number_list));

    let char_list = vec!['y', 'm', 'a', 'q'];
    println!("Largest char: {}", largest(&char_list));
}

Multiple Trait Bounds Syntax

You can require multiple traits for a generic type by using the + syntax, like T: TraitA + TraitB.

For complex bounds, you can also use a where clause after the function signature, which can make the signature cleaner:

fn some_function<T, U>(t: T, u: U) -> i32 where T: Display + Clone, U: Clone + Debug { /* ... */ }

Generic Structs

Just like functions, you can define structs to be generic over one or more type parameters. This allows your data structures to hold data of any specified type.

The Point<T> struct can hold coordinates of any type T (e.g., i32, f64).

struct Point<T> {
    x: T,
    y: T,
}

pub fn main() {
    let integer_point = Point {
        x: 5,
        y: 10
    };
    let float_point = Point {
        x: 1.0,
        y: 4.0
    };

    println!("Int Point: ({}, {})", 
             integer_point.x, integer_point.y);
    println!("Float Point: ({}, {})", 
             float_point.x, float_point.y);
}

Implementing Methods on Generic Structs

When implementing methods for a generic struct, you need to specify the generic type parameter(s) after impl.

You can also add trait bounds to methods if a method specifically requires certain behavior from its generic types.

struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn x(&self) -> &T {
        &self.x
    }
}

pub fn main() {
    let p = Point {
        x: 5,
        y: 10
    };
    println!("p.x = {}", p.x());
}

Generics and Performance

One of Rust's strengths is that generics are a zero-cost abstraction. This means using generics doesn't incur any runtime performance penalty.

Rust achieves this through monomorphization: at compile time, the compiler generates specialized versions of your generic code for each concrete type it's used with. So, largest<i32> and largest<char> become two distinct, optimized functions.

Test Your Knowledge

Which of the following statements about Rust generics are TRUE?

Recap: The Power of Generics

In this lesson, you've learned the fundamentals of writing generic code in Rust:

  • What they are: A way to write flexible, reusable code.
  • Generic functions: Using <T> for type parameters.
  • Trait bounds: Specifying required behaviors with T: Trait.
  • Generic structs: Creating data structures that hold generic types.
  • Zero-cost: Rust's generics compile to specific code, ensuring no runtime penalty.

Generics are a cornerstone of idiomatic Rust, enabling powerful, type-safe abstractions!

Preguntas frecuentes

¿La lección «Escritura de código genérico en Rust» es gratis?

Sí — el texto completo de «Escritura de código genérico en Rust» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Learn Rust Coding, actualiza a CoddyKit PRO. El curso de Learn Rust Coding incluye 3 lecciones en total.

¿Qué aprenderé en «Escritura de código genérico en Rust»?

Aprenda a escribir funciones y estructuras de datos que funcionen con varios tipos, mejorando la reutilización del código sin sacrificar la seguridad de tipos. Practicas Learn Rust Coding con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Learn Rust Coding?

No se requiere experiencia previa. Learn Rust Coding en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 3.

¿Cuánto tiempo toma la lección «Escritura de código genérico en Rust»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Learn Rust Coding?

Sí. Cada lección de Learn Rust Coding incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Escritura de código genérico en Rust
  2. Definición e implementación de traits
  3. Uso avanzado de traits: tipos asociados
← Volver a Learn Rust Coding