我想向模块添加一个静态变量,这样我就可以通过执行module_name::variable_name
来访问该变量。但是,我希望这个变量是枚举类型的向量。
我的意思是:
pub mod cards{
#[derive(Debug)]
pub enum SUIT{
CLUB, DIAMOND, HEART, SPADE,
}
pub const all_cards: Vec<SUIT> = vec![SUIT::CLUB, SUIT::DIAMOND, SUIT::HEART, SUIT::SPADE];
}
fn main(){
println!("{:?}", cards::all_cards);
}
但这样做会给我两个错误:
error[E0010]: allocations are not allowed in constants
和
error[E0015]: cannot call non-const fn `slice::<impl [SUIT]>::into_vec::<std::alloc::Global>` in constants
有没有一种方法可以在模块内声明枚举类型的向量?
在本例中,由于ALL_CARDS
的大小固定,因此可以使用Array。游乐场链接
use crate::cards::ALL_CARDS;
pub mod cards {
#[derive(Debug)]
pub enum SUIT {
CLUB,
DIAMOND,
HEART,
SPADE,
}
pub const ALL_CARDS: [SUIT; 4] = [SUIT::CLUB, SUIT::DIAMOND, SUIT::HEART, SUIT::SPADE];
}
fn main() {
println!("{:?}", ALL_CARDS);
}
矢量需要一个堆分配,并且正如错误消息所说的";不允许在常量中进行分配";。因此,当您需要一个全局静态数据,该数据需要在程序的生命周期内在堆上初始化一次时:https://crates.io/crates/once_cell或https://crates.io/crates/lazy_static
注意,根据Rust命名约定,我使用大写字母表示常数值
为什么不将其声明为array
?
pub mod cards{
#[derive(Debug, Clone, Copy)]
pub enum SUIT{
CLUB, DIAMOND, HEART, SPADE,
}
pub const all_cards: [SUIT; 4] = [SUIT::CLUB, SUIT::DIAMOND, SUIT::HEART, SUIT::SPADE];
}
fn main(){
println!("{:?}", cards::all_cards); // [CLUB, DIAMOND, HEART, SPADE]
}