假设我们有以下类型:
struct Wrapper(Content);
我通常需要访问此类型的
Content
值,每次解构都很麻烦。那么,展开此值的惯用方法是什么?我知道两种方法:实现Into<Content>
和实现Deref
。也许其中一种更可取?或者可能有更好的方式来完成吗?impl Into<Content> for Wrapper {
fn into(self) -> Content {
let Wrapper(content) = self;
content
}
}
// ...
let content: Content = wrapper.into();
Deref方法:
impl Deref for Wrapper {
type Target = Content;
fn deref(&self) -> &Self::Target {
let Wrapper(content) = self;
content
}
}
// ...
let content: Content = *wrapper;
&self.0
,你考虑过这点了吗?还是你在谈论如何从Wrapper
实现的外部使用这个类型? - rodrigo&self[0]
,但是出现了错误。无论如何,尽可能地让包装类型像内容类型一样被处理。所以,是的,我想经常在包装器外使用它。 - Miguel Bartelsman