Rust 常量表达式可以使用 Default 之类的特性吗?

pra*_*ara 4 default constants rust

这段代码给出了一个错误:

#[derive(Default)]
struct A {
    b: Option<()>,
    c: Option<()>,
}

const a: A = A {
    b: None,
    ..Default::default()
};
Run Code Online (Sandbox Code Playgroud)
error[E0015]: calls in constants are limited to constant functions, tuple structs and tuple variants
 --> src/lib.rs:9:7
  |
9 |     ..Default::default()
  |       ^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

在这个小例子中,这不是一个大问题,但是如果我有一个由多个实现该Default特征的结构组成的结构,那么无法使用它至少会带来不便。

虽然我可以写这个,但它没有提供以下灵活性Default

impl A {
    const fn new(b: Option<()>) -> Self {
        A { b, c: None }
    }
}

const a: A = A::new(None);
Run Code Online (Sandbox Code Playgroud)

有什么办法可以避免这样做吗?

Frx*_*rem 6

..Default::default()语法不限于Default::default(),所以你可以写一个const fn默认样的功能,并使用一个不变的那里面:

struct A {
    b: Option<()>,
    c: Option<()>,
}

impl A {
    const fn new() -> A {
        A {
            b: None,
            c: None,
        }
    }
}

impl Default for A {
    fn default() -> A {
        // implementing using new() instead of #[derive]
        // to avoid diverging implementations
        A::new()
    }
}

const a: A = A {
    b: None,
    ..A::new()
};
Run Code Online (Sandbox Code Playgroud)

在操场上奔跑

  • 您还可以将 `..DEFAULT_A` 与 `const DEFAULT_A: A = A { b: None, c: None };` 一起使用,您甚至不需要函数。 (2认同)