我写了一个可以返回结构A
或结构B
的函数,这些结构实现了Common
特性。我为函数的返回类型使用了语法-> impl Common
,但是由于类型不兼容,代码无法编译:
trait Common {
fn foo();
}
struct A;
impl Common for A {
fn foo() {
println!("Struct A");
}
}
struct B;
impl Common for B {
fn foo() {
println!("Struct B");
}
}
fn bar(param: &str) -> impl Common {
if param == "A" {
return A;
} else {
return B;
}
}
fn main() {
bar("A");
bar("B");
}
错误是:
error[E0308]: mismatched types
--> src/main.rs:25:16
|
21 | fn bar(param: &str) -> impl Common {
| ----------- expected because this return type...
22 | if param == "A" {
23 | return A;
| - ...is found to be `A` here
24 | } else {
25 | return B;
| ^ expected struct `A`, found struct `B`
|
= note: expected type `A`
found type `B`
在我的第一个实现中,我尝试在函数中使用模式匹配以使其更加惯用,但错误仍然存在:
match param {
"A" => A,
"B" => B,
_ => panic!("Invalid param"),
}
我该如何处理此类普通问题?