Don*_*yte 3 generic-programming rust
我有以下结构:
pub struct Foo<T> {
some_value: T,
}
impl<T> Foo<T> {
pub fn new(value: T) -> Self {
Self { some_value: value }
}
}
// Implement `Default()`, assuming that the underlying stored type
// `T` also implements `Default`.
impl<T> Default for Foo<T>
where
T: Default,
{
fn default() -> Self {
Self::new(T::default())
}
}
Run Code Online (Sandbox Code Playgroud)
Foo::default()如果T实现Default,我希望可用,否则不可用。
是否可以在 Rust 中指定“条件实现”,当且仅当满足某个泛型类型特征约束时,我们才实现特征?如果不满足约束,则不会实现目标特征(Default在本例中)并且没有编译器错误。
换句话说,是否可以通过以下方式使用上面的通用结构?
fn main() {
// Okay, because `u32` implements `Default`.
let foo = Foo::<u32>::default();
// This should produce a compiler error, because `Result` does not implement
// the `Default` trait.
//let bar = Foo::<Result<String, String>>::default();
// This is okay. The `Foo<Result<...>>` specialisation does not implement
// `Default`, but we're not attempting to use that trait here.
let bar = Foo::<Result<u32, String>>::new(Ok(42));
}
Run Code Online (Sandbox Code Playgroud)
对于此特定实例,由 提供的derive(Default)实现完全符合您的要求:
#[derive(Default)]
pub struct Foo<T> {
some_value: T,
}
Run Code Online (Sandbox Code Playgroud)
也可以看看:
| 归档时间: |
|
| 查看次数: |
1470 次 |
| 最近记录: |