我可以在 Rust 中将 const 与重载运算符一起使用吗? [英] Can I use const with overloading operators in Rust?

查看:54
本文介绍了我可以在 Rust 中将 const 与重载运算符一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中:

#![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)
    }
}

编译器说:

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;
  |                ^^^^^

最好的替代品是什么?

推荐答案

不,你不能.也就是说,add 的实现实际上可以做 Rust 可以做的任何,包括恐慌、打印输出、读取文件、分配内存等.

No, you cannot. Namely, the implementation of add could do literally anything that Rust can do, including panicking, printing output, reading files, allocating memory, etc.

您需要手动"构建常量:

You will need to construct your constant "by hand":

const B: Foo = Foo(2);

您还可以使用 构建脚本,它会生成 Rust 代码,然后您可以重新包含到您的程序中.

You could also utilize a build script which would generate Rust code that you then can include back into your program.

正如错误消息所说:

注意:通过 const fn

然而,这对你现在和现在都无济于事,因为目前无法制作特征方法 const,而且我怀疑 Add::add(或任何其他操作符trait) 将被标记为 const ,因为这会过于严格——阻止 Add 的实现使用上面列出的所有功能.我不知道专业化/子类型化将如何与 const 函数配合使用.

However, that won't help you here and now as trait methods cannot currently be made const, and I doubt that Add::add (or any other operator trait) will be marked const as that would be overly restrictive — preventing implementations of Add from using all the features listed above. I don't know how specialization / subtyping will work with const functions.

这篇关于我可以在 Rust 中将 const 与重载运算符一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆