0Pricing
Mojo Academy · Aula

Adicionando métodos a uma struct

Dê comportamento ao seu tipo.

Adicionando métodos a uma struct é uma aula grátis de Mojo Academy no CoddyKit. Esta é a aula 3 de 4. 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 Mojo Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Mojo Academy inclui 4 aulas no total.

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

Data Plus Behavior

So far your struct only holds data. A method is a function that lives inside the struct and gives your type behavior. 🚀

Methods Live Inside

You write a method by defining a function indented inside the struct, right alongside its fields and __init__.

struct Point:
    var x: Int
    var y: Int
    fn show(self):
        print(self.x, self.y)

self Comes First

A method's first parameter is self, the instance it was called on. Through self the method reads and uses the struct's own fields.

fn show(self):
    print(self.x)

Calling a Method

You call a method with dot syntax on an instance. Mojo passes that instance in as self automatically for you.

var p = Point(3, 4)
p.show()

Methods Can Return Values

Like any function, a method can return a result. Declare the return type after an arrow and hand back a value.

fn sum(self) -> Int:
    return self.x + self.y

Methods Take Arguments Too

After self, a method can accept more arguments, just like a normal function, to work with extra data the caller provides.

fn scaled(self, factor: Int) -> Int:
    return self.x * factor

Read-Only by Default

A plain self parameter is borrowed, so the method can read fields but not change them. This keeps your data safe.

Mutating with mut self

To let a method change the instance, mark the parameter mut self. Now assignments to self.x actually update the value.

fn move_right(mut self, step: Int):
    self.x += step

Methods Build on Each Other

One method can call another through self, so you compose small behaviors into larger ones without repeating code.

fn report(self):
    print(self.sum())

Encapsulation in Action

Keeping fields and the methods that use them in one struct is encapsulation. The type owns both its data and how that data behaves.

A Struct That Does Work

Here a Point both stores coordinates and reports their sum. Your type is now active, not just a passive data container.

struct Point:
    var x: Int
    var y: Int
    fn sum(self) -> Int:
        return self.x + self.y

Quick Check

Let us check what you know about methods.

Recap

You gave your struct methods that read and even mutate its fields. Next you will compare Mojo structs with Python classes. 🧩

Perguntas Frequentes

A aula “Adicionando métodos a uma struct” é grátis?

Sim — o texto completo de “Adicionando métodos a uma struct” é 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 Mojo Academy, atualize para CoddyKit PRO. O curso de Mojo Academy inclui 4 aulas no total.

O que vou aprender em “Adicionando métodos a uma struct”?

Dê comportamento ao seu tipo. Você pratica Mojo Academy 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 Mojo Academy?

Nenhuma experiência prévia é necessária. Mojo Academy 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 3 de 4.

Quanto tempo leva a aula “Adicionando métodos a uma struct”?

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 Mojo Academy?

Sim. Cada aula de Mojo Academy 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. Definindo uma struct
  2. Campos e o método __init__
  3. Adicionando métodos a uma struct
  4. Structs versus classes Python
← Voltar para Mojo Academy