我在我的项目中有一个结构A,它在逻辑上与来自不同机箱的结构B相关。两者在内部都有一个可选的子结构(C / D)。
让我们假设在这个例子中,他们有这样的结构定义:
struct D {
name: Option<String>
}
struct B {
spec: Option<D>
}
struct C {
name: Option<String>
}
struct A {
spec: Option<C>
}现在,我想将A上的Into-trait实现到B中
impl Into<D> for C {
fn into(self) -> D {
D {
name: self.name
}
}
}
impl Into<B> for A {
fn into(self) -> B {
B {
spec: self.spec.into()
}
}
}但铁锈不允许这样做:
error[E0277]: the trait bound `std::option::Option<D>: From<std::option::Option<C>>` is not satisfied
--> src\model\k8s.rs:615:29
|
615 | spec: self.spec.into()
| ^^^^ the trait `From<std::option::Option<C>>` is not implemented for `std::option::Option<D>`
|
= help: the following implementations were found:
<std::option::Option<&'a T> as From<&'a std::option::Option<T>>>
<std::option::Option<&'a mut T> as From<&'a mut std::option::Option<T>>>
<std::option::Option<&'a tracing_core::span::Id> as From<&'a tracing::span::EnteredSpan>>
<std::option::Option<&'a tracing_core::span::Id> as From<&'a tracing::span::Span>>
and 10 others
= note: required because of the requirements on the impl of `Into<std::option::Option<D>>` for `std::option::Option<C>`尽管我在C上为Into提供了一个自定义实现,但它只检查From。我不能提供,因为D是另一个板条箱。
我必须这样写:
spec: if let Some(v) = self.spec { Some(v.into()) } else { None }现在的问题是:有没有更好的方式让我失踪?如果不是:为什么into()选项如此麻烦?
发布于 2021-06-11 16:33:11
问题是您调用的是Option<C>类型的Into::into,而不是Option持有的类型(C)。
您可以使用对Option的内部类型进行操作的Option::map方法
impl Into<B> for A {
fn into(self) -> B {
B {
spec: self.spec.map(Into::into)
}
}
}在标准库中没有全面的impl<T, U: Into<T>> Into<Option<T>> for Option<U> (或From等效项),这就是为什么您不能使用Into特征直接在Option上将Option<T>转换为Option<U>,而必须依赖于Option::map或其他方法(如您的最后一个代码片段)来提取内部类型。
https://stackoverflow.com/questions/67933310
复制相似问题