Can I use const with overloading operators in Rust?

Viewed 622

In this code:

#![allow(dead_code)]
use std::ops::Add;
struct Foo(i32);

const X: i32 = 1;
const Y: i32 = X + X;
const A: Foo = Foo(1);
const B: Foo = A + A;

impl Add for Foo {
    type Output = Foo;
    fn add(self, rhs: Foo) -> Foo {
        Foo(self.0 + rhs.0)
    }
}

The compiler says:

error[E0015]: calls in constants are limited to struct and enum constructors
 --> src/main.rs:8:16
  |
8 | const B: Foo = A + A;
  |                ^^^^^
  |
note: a limited form of compile-time function evaluation is available on a nightly compiler via `const fn`
 --> src/main.rs:8:16
  |
8 | const B: Foo = A + A;
  |                ^^^^^

What is the best substitution?

1 Answers
Related