我正在阅读 an article这表明 Rust 有一个编译器选项来禁用堆分配:
Rust has a number of standard library features that rely on the heap, like boxes. However, Rust has compiler directives to completely disable any heap-using language features, and statically verify that none of these features are being used. It is entirely practical to write a Rust program with no heap usage.
在编译时检查任何错误的堆分配的能力对我来说非常有值(value)。你如何在 Rust 中做到这一点?我在 rustc man page 中没有看到任何相关标志.
最佳答案
没有这样的编译器标志,虽然我不认为那是这篇文章的意思:
Rust has compiler directives
我会将“指令”解析为一个属性,类似于#[foo]
。据我所知,目前还没有实现此目标的特性。
请注意,您的文章早于 Rust 1.0:
Rust, version 0.11
最接近的是避免使用标准库,只使用 the core library .这避开了 liballoc
的使用,这是分配的主要机制。这样做可以防止像 Box
或 String
这样的类型存在,这是一个非常强大的静态保证。
#![no_std]
pub fn example() {
Box::new(42);
}
error[E0433]: failed to resolve. Use of undeclared type or module `Box`
--> src/lib.rs:4:5
|
4 | Box::new(42);
| ^^^ Use of undeclared type or module `Box`
但是,没有什么能阻止您重写 liballoc 中的相同代码并自行分配内存。您还可以链接到分配内存的现有库。没有神奇的编译器 channel 可以检测堆分配。
另见:
关于rust - 禁用堆分配的 Rust 编译器标志是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51934079/