0Pricing
Learn Rust Coding · Aula

Definição e Utilização de Estruturas

Crie estruturas de dados personalizadas com estruturas, incluindo estruturas de tuplo e semelhantes a unidades, para agrupar dados relacionados.

Definição e Utilização de Estruturas é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 1 de 3. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 3 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Meet Structs: Custom Data Types

In Rust, structs (short for structures) are a way to create custom data types that let you name and package together multiple related values into a meaningful group.

Think of a struct as a blueprint for a user, a color, or a point in space. Instead of having separate variables for a user's name, email, and age, you can put them all inside a User struct.

This helps you organize your data logically and make your code easier to read and maintain.

Defining a Classic Struct

The most common type of struct is a classic struct, where you name each piece of data, called a field. Here's how you define one:

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {
    // This code only defines the struct blueprint.
    // No actual user has been created yet!
    println!("Struct 'User' blueprint defined.");
}

Creating Struct Instances

Once you define a struct, you can create concrete instances of it. Each instance holds specific values for its fields. You create an instance by specifying concrete values for each field.

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {
    let user1 = User {
        email: String::from("alice@example.com"),
        username: String::from("alice123"),
        active: true,
        sign_in_count: 1,
    };
    println!("User instance created!");
}

Accessing Struct Fields

To get data out of a struct instance, you use dot notation. Simply type the instance name, a dot (.), and then the field name.

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {
    let user1 = User {
        email: String::from("alice@example.com"),
        username: String::from("alice123"),
        active: true,
        sign_in_count: 1,
    };
    println!("User's username: {}", user1.username);
    println!("User's email: {}", user1.email);
}

Mutability with Structs

Just like regular variables, entire struct instances can be made mutable using the mut keyword. If an instance is mutable, all of its fields can be changed.

You cannot make only certain fields mutable; the mutability applies to the struct instance as a whole.

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {
    let mut user1 = User {
        email: String::from("alice@example.com"),
        username: String::from("alice123"),
        active: true,
        sign_in_count: 1,
    };
    
    println!("Old email: {}", user1.email);
    user1.email = String::from("new_alice@example.com");
    println!("New email: {}", user1.email);
}

Tuple Structs: Unnamed Fields

Tuple structs are another form of struct that look like tuples but have a name. They're useful when you want to give a tuple a distinct type name, but don't need to name its individual fields.

For example, Color(i32, i32, i32) is a named tuple that groups three integers together.

struct Color(i32, i32, i32);
struct Point(i32, i32, i32);

fn main() {
    let black = Color(0, 0, 0);
    let origin = Point(0, 0, 0);
    println!("Tuple structs 'Color' and 'Point' defined.");
}

Using Tuple Structs

Creating an instance of a tuple struct is similar to creating a regular tuple. To access the values inside, you use dot notation with their index, starting from 0.

struct Color(i32, i32, i32);
struct Point(i32, i32, i32);

fn main() {
    let black = Color(0, 0, 0);
    let origin = Point(0, 0, 0);

    println!("Black color: R={}, G={}, B={}", black.0, black.1, black.2);
    println!("Origin point: X={}, Y={}, Z={}", origin.0, origin.1, origin.2);
}

Unit-Like Structs: Markers

You can also define structs that have no fields at all. These are called unit-like structs because they behave similarly to the unit type ().

They are often used as markers to implement a particular trait on a type, where the data itself is not important.

struct AlwaysTrue;

fn main() {
    let subject = AlwaysTrue;
    // Unit-like structs don't store data directly,
    // but they can be instantiated and used as types.
    println!("Unit-like struct 'AlwaysTrue' created.");
}

Struct Update Syntax

If you need to create a new struct instance based on an existing one, but only want to change some field values, Rust offers a convenient struct update syntax (..).

This syntax moves the remaining fields from the specified instance, so the original instance can no longer be used if it contains fields that implement Copy.

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {
    let user1 = User {
        email: String::from("alice@example.com"),
        username: String::from("alice123"),
        active: true,
        sign_in_count: 1,
    };

    let user2 = User {
        email: String::from("bob@example.com"),
        username: String::from("bob456"),
        ..user1 // Copy remaining fields from user1
    };

    println!("User 2 email: {}", user2.email);
    println!("User 2 active: {}", user2.active);
    // user1.username is now moved, so user1 can't be used here.
}

Structs Quiz

Test your understanding of Rust structs.

Recap: Structs Overview

You've learned how to define and use structs in Rust!

  • Classic structs group named fields to create custom data types.
  • Tuple structs are named tuples, useful when field names aren't strictly necessary.
  • Unit-like structs have no fields and act as markers.
  • Struct instances can be made mut to allow modification of their fields.
  • The .. syntax helps create new instances from existing ones.

Structs are fundamental for organizing related data in Rust programs, making your code more structured and readable.

Perguntas Frequentes

A aula “Definição e Utilização de Estruturas” é grátis?

Sim — o texto completo de “Definição e Utilização de Estruturas” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 3 aulas no total.

O que vou aprender em “Definição e Utilização de Estruturas”?

Crie estruturas de dados personalizadas com estruturas, incluindo estruturas de tuplo e semelhantes a unidades, para agrupar dados relacionados. Você pratica Learn Rust Coding com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Learn Rust Coding?

Nenhuma experiência prévia é necessária. Learn Rust Coding no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 3.

Quanto tempo leva a aula “Definição e Utilização de Estruturas”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Learn Rust Coding?

Sim. Cada aula de Learn Rust Coding inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Definição e Utilização de Estruturas
  2. Enumerações para Tipos Personalizados
  3. Correspondência Poderosa de Padrões
← Voltar para Learn Rust Coding