0Pricing
Learn Rust Coding · Lección

Tipos compuestos

Tuplas y arrays

Tipos compuestos es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 3 de 4. 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 4 lecciones en total.

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

What Are Compound Types?

Compound types group multiple values into one. Rust has two primitive compound types:

  • Tuples — fixed-size groups of possibly different types.
  • Arrays — fixed-size groups of the same type.
fn main() {
    let tup = (1, 2.0, 'c');
    let arr = [10, 20, 30];
    println!("{} {}", tup.0, arr[0]);
}

Creating Tuples

A tuple bundles values inside parentheses. Each element can be a different type.

The tuple's type is the combination of its element types.

fn main() {
    let person: (&str, u32, f64) = ("Alice", 30, 5.6);
    println!("{} is {} years old", person.0, person.1);
}

Accessing Tuple Elements

Access tuple elements by index using a dot, starting at 0.

  • tup.0 is the first element.
  • tup.1 is the second.
fn main() {
    let point = (3, 7);
    let x = point.0;
    let y = point.1;
    println!("x={} y={}", x, y);
}

Destructuring Tuples

You can break a tuple into separate variables in one step. This is called destructuring.

fn main() {
    let coords = (1.5, 2.5, 3.5);
    let (a, b, c) = coords;
    println!("{} {} {}", a, b, c);
}

The Unit Type

An empty tuple () is called the unit type. It represents 'no meaningful value'.

Functions that return nothing actually return ().

fn main() {
    let nothing = ();
    println!("unit value is {:?}", nothing);
}

Creating Arrays

An array holds multiple values of the same type with a fixed length, written in square brackets.

Its type is [type; length].

fn main() {
    let days: [&str; 3] = ["Mon", "Tue", "Wed"];
    let numbers = [1, 2, 3, 4, 5];
    println!("{} {}", days[1], numbers[4]);
}

Array Indexing

Access array elements with square brackets and a zero-based index.

Accessing an out-of-bounds index causes a runtime panic — Rust checks bounds for safety.

fn main() {
    let colors = ["red", "green", "blue"];
    println!("first {}", colors[0]);
    println!("last {}", colors[2]);
}

Repeated Initial Values

To fill an array with the same value, use [value; count].

This creates an array of count elements all equal to value.

fn main() {
    let zeros = [0; 5];
    println!("{:?}", zeros);
    println!("length is {}", zeros.len());
}

Array Length

The .len() method returns the number of elements in an array. Length is fixed at compile time.

If you need a growable list, use a Vec instead.

fn main() {
    let scores = [88, 92, 75, 100];
    println!("there are {} scores", scores.len());
}

Iterating an Array

Use a for loop to visit each element of an array in order.

fn main() {
    let nums = [2, 4, 6, 8];
    let mut sum = 0;
    for n in nums {
        sum += n;
    }
    println!("sum = {}", sum);
}

Tuples vs Arrays

When to use each:

  • Use a tuple for a fixed group of different types, like a coordinate plus a label.
  • Use an array for a fixed group of the same type, like a list of scores.
fn main() {
    let record = ("Bob", [90, 85, 95]);
    println!("{} first score {}", record.0, (record.1)[0]);
}

Quick Check

Choose the correct statement about Rust compound types.

Recap

Rust's compound types:

  • Tuples — (a, b, c), mixed types, accessed by .0, destructurable.
  • Arrays — [a, b, c], same type, fixed length, accessed by [index].
  • () is the unit type.
fn main() {
    let (name, scores) = ("Cara", [70, 80, 90]);
    let mut total = 0;
    for s in scores {
        total += s;
    }
    println!("{} total {}", name, total);
}

Preguntas frecuentes

¿La lección «Tipos compuestos» es gratis?

Sí — el texto completo de «Tipos compuestos» 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 4 lecciones en total.

¿Qué aprenderé en «Tipos compuestos»?

Tuplas y arrays 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 3 de 4.

¿Cuánto tiempo toma la lección «Tipos compuestos»?

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. let y mutabilidad
  2. Tipos escalares
  3. Tipos compuestos
  4. Sombreado
← Volver a Learn Rust Coding