In dem folgenden Programm (play) bietet die FooBar
-Eigenschaft die bar
-Methode, aber der tatsächliche Typ des Objekts, das von bar
zurückgegeben wird, scheint ausgeblendet zu sein. Wenn ich ein Typ-Argument anstelle eines zugeordneten Typs verwende, funktioniert es (play).Typ Anmerkungen erforderlich - Warum werden zugeordnete Typen anders behandelt?
Warum werden zugeordnete Typen anders behandelt? Oder mache ich es falsch?
use std::ops::DerefMut;
pub trait FooBar: Sized {
type Assoc: Sized + DerefMut<Target=Self>;
fn foo(&mut self) -> Option<Self::Assoc>;
fn bar(mut this: Self::Assoc) -> Result<Self::Assoc, Self::Assoc> {
unimplemented!()
}
}
#[derive(Debug)]
struct Test(u32);
impl FooBar for Test {
type Assoc = Box<Test>;
fn foo(&mut self) -> Option<Self::Assoc> {
unimplemented!()
}
}
fn main() {
let mut tt = Test(20);
let tt_foo: Box<Test> = tt.foo().unwrap(); // this is ok
let tt_bar: Box<Test> = FooBar::bar(Box::new(tt)).unwrap(); // but not this
assert_eq!(tt_bar.0, 20);
}