Trait Deref per puntatori intelligenti in Rust

Livello 5335 battiture

Implementare Deref permette a *m di raggiungere il valore interno e abilita la deref coercion: chiamando hello, &MyBox<String> diventa automaticamente &String e poi &str.

Codice Rust

// Deref è il trait dietro l'operatore *
1use std::ops::Deref;
2
// Una struct tupla che avvolge un valore di tipo T
3struct MyBox<T>(T);
4
5impl<T> MyBox<T> {
// Costruttore che avvolge solo x (memorizzato direttamente, non nell'heap)
6 fn new(x: T) -> MyBox<T> {
7 MyBox(x)
8 }
9}
10
11impl<T> Deref for MyBox<T> {
// Dereferenziare un MyBox<T> dà un T
12 type Target = T;
13 fn deref(&self) -> &T {
// Restituisce un riferimento al valore interno; *m significa *(m.deref())
14 &self.0
15 }
16}
17
// Accetta un semplice &str
18fn hello(name: &str) {
19 println!("Hello, {}!", name);
20}
21
22fn main() {
// Avvolge una String in MyBox
23 let m = MyBox::new(String::from("Rust"));
// Deref coercion: &MyBox<String> → &String → &str; stampa Hello, Rust!
24 hello(&m);
// *m raggiunge la String interna: stampa Value: Rust
25 println!("Value: {}", *m);
26}

Output

Hello, Rust!
Value: Rust
Esercitati a digitare questo codice

Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.

Simboli in questo codice

I simboli che digiti in questo codice Rust e quante volte compaiono.

  • :× 11
  • (× 11
  • )× 11
  • {× 8
  • }× 8
  • >× 8
  • ;× 7
  • "× 6
  • <× 6
  • &× 5

Altri esempi Rust di livello 5

← Pratica di digitazione Rust