Usare le Struct in Rust

Mattepuffo's logo
Usare le Struct in Rust

Usare le Struct in Rust

Le Struct sono strutture dati che ci permettono di avere tipi diversi per ogni item.

La loro implementazione in Rust è simile a quella degli altri linguaggi.

Inoltre è possibile anche creare delle funzioni per le Struct, da richiamare poi nel nostro codice.

Vediamo un esempio:


// TRE CAMPI
struct Persona {
    nome: String,
    eta: u32,
    guadagni: u32,
}

// IMPLEMENTIAMO LA STRUCT CREANDO
// UNA FUNZIONE CHE CALCOLA I GUADAGNI
impl Persona {
    fn totAnno(&self) -> u32 {
        return self.guadagni * 12;
    }
}

fn main() {
    // PRIMA STRUCT
    let p1 = Persona {
        nome: String::from("Gino"),
        eta: 45,
        guadagni: 1000,
    };

    // SECONDA SCRUCT
    // IMPOSTATA COME MUT, ED È QUINDI POSSIBILE
    // MODIFICARE I VALORI
    let mut p2 = Persona {
        nome: String::from("Giampa"),
        eta: 45,
        guadagni: 500,
    };
    p2.eta = 30;

    // STAMPIAMO ALCUNI DATI DELLA PRIMA
    println!("{}", p1.nome);
    println!("{}", p1.totAnno());

    // STAMPIAMO ALCUNI DATI DELLA SECONDA
    println!("{}", p2.eta);
}

Come vedete abbiamo impostato anche come mut una delle due, per vedere che è possibile modificare i dati.

Inoltre abbiamo creato una funzione, usando impl per implementare le Struct.

Enjoy!


Condividi

Commentami!