Diciamo che ho qualche tratto:Implementazione Prendere in prestito <Trait> per un tipo che implementa Trait
trait MyTrait {
fn function1(&self);
}
e un certo tipo che lo implementa:
struct MyStruct {
number: i32,
}
impl MyTrait for MyStruct {
fn function1(&self) {
printn!("{}", self.number);
}
}
Ora ho un altro tipo, che vuole prendere cose che implementano MyTrait
. Non gli importa se sono di proprietà o meno. Dalla lettura in giro, sembra che il modo giusto per farlo è quello di prendere lo Borrow<X>
invece di X
o &X
o qualsiasi altra cosa. Questo gli permette di prendere le cose di tipo X
, o Rc<X>
o Box<X>
, ecc ...
Ho questo lavoro quando X
è un tipo concreto, ma come faccio a farlo funzionare quando X
è un tratto?
Ecco quello che ho provato prima:
struct Consumer<T> {
inner: T
}
impl<T: Borrow<MyTrait>> Consumer<T> {
pub fn new(inner: T) -> Consumer<T> {
Consumer {
inner: inner
}
}
pub fn do_stuff(&self) {
self.inner.borrow().function1();
}
}
fn main() {
// I want to eventually be able to swap this out for x = Rc::new(MyStruct ...
// but I'll keep it simple for now.
let x = MyStruct { number: 42 };
let c = Consumer::new(x);
c.do_stuff();
}
Questo non funziona ancora, perché MyStruct
implementa Borrow<MyStruct>
, ma non Borrow<MyTrait>
. Va bene, quindi cerchiamo di attuare tale:
impl Borrow<MyTrait> for MyStruct {
fn borrow(&self) -> &MyTrait {
self
}
}
Ciò mi dà il seguente errore, che non capisco:
<anon>:33:5: 35:6 error: method `borrow` has an incompatible type for trait: expected bound lifetime parameter , found concrete lifetime [E0053] <anon>:33 fn borrow(&self) -> &MyTrait { <anon>:34 self <anon>:35 } <anon>:33:5: 35:6 help: see the detailed explanation for E0053 error: aborting due to previous error playpen: application terminated with error code 101
Che cosa? Non vi è alcuna esistenza concreta menzionata in quel luogo e lo Borrow
viene definito senza alcuna durata menzionata. Sono perplesso.
In primo luogo, le mie ipotesi sono corrette sul fatto che l'utilizzo di Borrow
è la giusta soluzione? E se sì, come posso implementare lo Borrow
di un tratto?
Ah, grazie! Non avevo mai visto prima questa sintassi '& (MyTrait + 'a)'. L'ho visto in parametri generici ad altri tipi, o in bound type, ma mai da solo prima. –