【发布时间】:2014-11-21 16:52:12
【问题描述】:
我问了一个类似的 question earlier,它帮助我了解了幕后发生的事情,但在泛型编程方面,我仍然无法让 Rust 做我希望它做的事情.这是一些代码:
struct Foo<B: Bar> { bars: Vec<Box<B>> }
struct Foo2;
trait Bar {}
impl Bar for Foo2 {}
impl<B: Bar> Foo<B> {
fn do_something() -> Foo<B> {
let foo2:Box<Bar> = box Foo2;
let mut foo = Foo { bars: vec!(box Foo2) };
foo.bars.push(box Foo2);
foo // compiler: *ERROR*
}
}
错误:expected 'Foo<B>', found 'Foo<Foo2>'
- 如何给编译器提示或明确告诉编译器
foo(Foo) 实现了Bar(B: Bar)? - 这是一个错误吗?我应该推迟使用 Rust 直到它达到 1.0 吗?
版本:0.12.0-nightly (4d69696ff 2014-09-24 20:35:52 +0000)
我在@Levans 的解决方案中看到的问题:
struct Foo2;
struct Foo3 {
a: int
}
trait Bar {
fn create_bar() -> Self;
}
impl Bar for Foo2 {
fn create_bar() -> Foo2 { Foo2 } // will work
}
impl Bar for Foo3 {
fn create_bar(a: int) -> Foo3 { Foo3 {a: a} } // will not work
}
错误:method 'create_bar' has 1 parameter but the declaration in trait 'Bar::create_bar' has 0
另外,我注意到了这一点:Bar::create_bar()。 Rust 怎么知道使用 Foo2 的实现?
【问题讨论】:
标签: rust