mi piacerebbe implementare Deref
e DefrefMut
su una struttura che possiede un tratto in scatola, per esempio:Implementazione Deref su una struttura che possiede una caratteristica scatola
use std::ops::{Deref, DerefMut};
trait Quack {
fn quack(&self);
}
struct QuackWrap {
value: Box<Quack>
}
impl Deref for QuackWrap {
type Target = Box<Quack>;
fn deref<'a>(&'a self) -> &'a Box<Quack> {
&self.value
}
}
impl DerefMut for QuackWrap {
fn deref_mut<'a>(&'a mut self) -> &'a mut Box<Quack> {
&mut self.value
}
}
Questo non riesce a compilare con il seguente errore:
src/main.rs:14:5: 16:6 error: method `deref` has an incompatible type for trait: expected bound lifetime parameter 'a, found concrete lifetime [E0053]
src/main.rs:14 fn deref<'a>(&'a self) -> &'a Box<Quack> {
src/main.rs:15 &self.value
src/main.rs:16 }
src/main.rs:20:5: 22:6 error: method `deref_mut` has an incompatible type for trait: expected bound lifetime parameter 'a, found concrete lifetime [E0053]
src/main.rs:20 fn deref_mut<'a>(&'a mut self) -> &'a mut Box<Quack> {
src/main.rs:21 &mut self.value
src/main.rs:22 }
Se sostituisco Box<Quack>
con Box<String>
(o un tipo simile), funziona. Il problema è che Quack
è un tratto. Ma non sono sicuro del perché abbia generato il messaggio di errore. Qualche idea?
La mia domanda è simile a another SO question, ma non proprio la stessa. In quella domanda, la struct ha un parametro type con il tratto come un vincolo. Mentre nella mia domanda, non esiste un parametro di tipo.
Non voglio confondere i problemi, ma c'è una buona ragione per cui ho bisogno di Box<Quack>
nella mia applicazione. Cioè Non riesco a sostituire Quack
con un parametro di tipo. Nel caso ti interessi, il motivo è discussed further in another SO question.
'type Target = Box;' è 'tipo Target = Box ;', e '&' a Box ' è '& 'a Box '. –