如何在const结构中初始化BTreeMap?

时间:2019-04-13 05:25:54

标签: rust const

如何在BTreeMap结构中初始化const

use std::collections::BTreeMap;

struct Book {
    year: u16,
    volume: u8,
    amendment: u8,
    contents: BTreeMap<String, String>,
}

const BOOK1: Book = Book {
    year: 2019,
    volume: 1,
    amendment: 0,
    contents: BTreeMap::new(), // Issue here
};
error[E0015]: calls in constants are limited to constant functions, tuple structs and tuple variants
  --> src/lib.rs:14:15
   |
14 |     contents: BTreeMap::new(),
   |               ^^^^^^^^^^^^^^^

1 个答案:

答案 0 :(得分:2)

不能。从Rust 1.34.0开始,对于const,没有标记为BTreeMap的函数。这就是为什么您根本无法定义const BtreeMap的原因。

唯一的方法是使用静态变量和lazy_static crate的用法。

use lazy_static::lazy_static; // 1.3.0
use std::collections::BTreeMap;

lazy_static! {
    static ref BOOK1: Book = Book {
        year: 2019,
        volume: 1,
        amendment: 0,
        contents: BTreeMap::new()
    };
}