rust - 如何为通用结构实现默认值?

标签 rust

我有一个通用结构,想提供一个具体的默认实现,它也将允许用户覆盖默认字段的值,但我遇到了编译错误:

struct MyStruct<A, B, C> {
    pub a: A,
    pub b: B,
    pub c: C,
}

impl<A, B, C> MyStruct<A, B, C>
where
    A: Trait1,
    B: Trait2,
    C: Trait3,
{
    pub fn foo() {}
}

trait Trait1 {}
trait Trait2 {}
trait Trait3 {}

我可以显式地创建 MyStruct 的实例:

struct SomeA();
impl Trait1 for SomeA {}
struct SomeB();
impl Trait2 for SomeB {}
struct SomeC();
impl Trait3 for SomeC {}

let a = SomeA();
let b = SomeB();
let c = SomeC();

let my_struct = MyStruct { a: a, b: b, c: c }; // compiles

现在我想实现 Default,这也将允许在必要时使用不同的值覆盖特定字段(允许部分默认?)。不确定语法:

impl Default for MyStruct<SomeA, SomeB, SomeC> {
    fn default() -> Self {
        ...
    }
}

Playground

最佳答案

如果 ABC 都实现了 ,您可以通过仅实现 Default 来实现这一点>默认:

impl <A, B, C> Default for MyStruct<A, B, C> where A: Default, B: Default, C: Default {
    fn default() -> Self {
        Self {
            a: A::default(),
            b: B::default(),
            c: C::default(),
        }   
    }   
}

关于rust - 如何为通用结构实现默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64412172/

相关文章:

rust - 用于对象拾取的整数纹理的 Alpha 混合

rust - 如何使结构可调用?

rust - Future::then 的语义是什么?

rust - 如何使用 Hyper 通过代理访问 HTTPS 站点?

rust - 如何引用数组中的多个成员?

rust - 如何在 Rust 中使用标准输出保存图像?

rust - 如何找到 `derive` 中使用的符号的定义位置?

rust - 在线程内使用闭包

rust - 为什么不能在同一结构中存储值和对该值的引用?

rust - 如何将方法作为回调/处理程序参数传递给函数? [复制]