我正在try 从函数返回特征对象的装箱结果.我的函数返回(似乎)满足该特征对象的正确类型.然而,编译器说类型不匹配.以下是我的代码:
use anyhow::Result;
#[derive(Debug)]
struct Bar {
a: i32,
b: i32,
}
trait Wrap {}
struct Wrapper1<'a> {
bar: &'a Bar,
}
impl<'a> Wrapper1<'a> {
fn new(bar: &'a Bar) -> Result<Self> {
Ok(Self { bar })
}
}
impl<'a> Wrap for Wrapper1<'a> {}
struct Wrapper2<'a> {
bar: &'a Bar,
}
impl<'a> Wrapper2<'a> {
fn new(bar: &'a Bar) -> Result<Self> {
Ok(Self { bar })
}
}
impl<'a> Wrap for Wrapper2<'a> {}
fn wrap<'a>(i: i32, bar: &'a Bar) -> Result<Box<dyn Wrap + 'a>> {
if i % 2 == 0 {
Wrapper1::new(bar).map(Box::new)
} else {
Wrapper2::new(bar).map(Box::new)
}
}
这就是我得到的错误.
error[E0308]: mismatched types
--> src/main.rs:37:9
|
35 | fn wrap<'a>(i: i32, bar: &'a Bar) -> Result<Box<dyn Wrap + 'a>> {
| -------------------------- expected `Result<Box<(dyn Wrap + 'a)>, anyhow::Error>` because of return type
36 | if i % 2 == 0 {
37 | Wrapper1::new(bar).map(Box::new)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Result<Box<dyn Wrap>, Error>`, found `Result<Box<Wrapper1<'_>>, Error>`
|
= note: expected enum `Result<Box<(dyn Wrap + 'a)>, _>`
found enum `Result<Box<Wrapper1<'_>>, _>`
help: use `?` to coerce and return an appropriate `Err`, and wrap the resulting value in `Ok` so the expression remains of type `Result`
|
37 | Ok(Wrapper1::new(bar).map(Box::new)?)
| +++ ++
error[E0308]: mismatched types
--> src/main.rs:39:9
|
35 | fn wrap<'a>(i: i32, bar: &'a Bar) -> Result<Box<dyn Wrap + 'a>> {
| -------------------------- expected `Result<Box<(dyn Wrap + 'a)>, anyhow::Error>` because of return type
...
39 | Wrapper2::new(bar).map(Box::new)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Result<Box<dyn Wrap>, Error>`, found `Result<Box<Wrapper2<'_>>, Error>`
|
= note: expected enum `Result<Box<(dyn Wrap + 'a)>, _>`
found enum `Result<Box<Wrapper2<'_>>, _>`
help: use `?` to coerce and return an appropriate `Err`, and wrap the resulting value in `Ok` so the expression remains of type `Result`
|
39 | Ok(Wrapper2::new(bar).map(Box::new)?)
| +++ ++
For more information about this error, try `rustc --explain E0308`.
error: could not compile `foo` due to 2 previous errors
编译器建议这样包装我的表达式,这确实有效.
Ok(Wrapper2::new(bar).map(Box::new)?)
+++ ++
然而,我不明白为什么这是必要的,因为它似乎使类型完全相同.它也不太符合人体工程学.