0Pricing
Mojo Academy · Lezione

Aggiungere metodi a una struct

Dia un comportamento al proprio tipo.

Aggiungere metodi a una struct è una lezione Mojo Academy gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Mojo Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Mojo Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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. 🧩

Domande Frequenti

La lezione «Aggiungere metodi a una struct» è gratuita?

Sì — il testo completo di «Aggiungere metodi a una struct» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Mojo Academy, passa a CoddyKit PRO. Il corso Mojo Academy include 4 lezioni in totale.

Cosa imparerò in «Aggiungere metodi a una struct»?

Dia un comportamento al proprio tipo. Eserciti Mojo Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Mojo Academy?

Non è richiesta alcuna esperienza precedente. Mojo Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Aggiungere metodi a una struct»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Mojo Academy?

Sì. Ogni lezione Mojo Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Definire una struct
  2. Campi e metodo __init__
  3. Aggiungere metodi a una struct
  4. Struct e classi Python a confronto
← Torna a Mojo Academy