我一直在使用Rust进行特性的尝试,但遇到了一个问题。以下是一些代码:
struct Foo;
trait Bar {}
impl Bar for Foo {}
fn bar<B: Bar>(bar: B) {}
fn barr<B: Bar>() {
bar(Foo); // 1. THIS WILL WORK
let foo: B = Foo; // 2. THIS WILL NOT WORK
let foo_vec: Vec<B> = vec![Foo]; // 3. THIS WILL NOT WORK
}
这会产生以下错误:
error[E0308]: mismatched types
--> src/main.rs:11:18
|
11 | let foo: B = Foo; // 2. THIS WILL NOT WORK
| ^^^ expected type parameter, found struct `Foo`
|
= note: expected type `B`
found type `Foo`
error[E0308]: mismatched types
--> src/main.rs:12:32
|
12 | let foo_vec: Vec<B> = vec![Foo]; // 3. THIS WILL NOT WORK
| ^^^ expected type parameter, found struct `Foo`
|
= note: expected type `_`
found type `Foo`
为什么#2和#3不能工作?我如何让编译器知道Foo
确实有一个Bar
impl
?
另一个例子:
struct Foo<B: Bar> {
bar: Option<B>,
}
struct Foo2;
trait Bar {}
impl<B: Bar> Bar for Foo<B> {}
impl Bar for Foo2 {}
fn bar<B: Bar>(bar: B) {}
fn circle_vec<B: Bar>() {
bar(Foo2); // 1. WORKS
Foo { bar: Some(Foo { bar: None }) }; // 2. WILL NOT WORK
}
这会导致出现以下错误:
error[E0282]: type annotations needed
--> src/main.rs:17:21
|
17 | Foo { bar: Some(Foo { bar: None }) }; // 2. WILL NOT WORK
| ^^^ cannot infer type for `B`
fn barr<B: Bar>() { let foo_vec: Vec<Box<B>> ...}
不能工作?或者它可以工作,只是我漏掉了什么? - gooB
可能不是Foo
。要向向量中添加元素,您需要具有类型B
的值,通常作为函数参数接收(fn barr<B: Bar>(x: B)
)。 - Francis Gagné