2

How do I initialize a BTreeMap within a const struct?

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(),
   |               ^^^^^^^^^^^^^^^
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user1406186
  • 940
  • 3
  • 16
  • 28
  • 1
    For the future: ***Always*** include a [mcve]. This means, that your code should be able to compile (unless you have an error in your code that you want us to solve). **But** all needed, externals should be included as well as all definition of structs, mods, etc. Please see the [rust info tag](https://stackoverflow.com/tags/rust/info) and the section *Producing a Minimal, Complete, Verifiable example for Rust code*. It contains very valuable information. – hellow Apr 13 '19 at 05:44
  • Thanks, am I missing something else? I'm not sure what else to add? I'm new to rust sorry – user1406186 Apr 13 '19 at 05:46
  • 2
    First of, for your actual problem `year`, `volume`, `amendment` are not necessary. You could just leave them out. Next `book_content_node::book_content_node` is not defined, nor needed. Just replace it by something simple like `u32`. – hellow Apr 13 '19 at 05:48
  • 1
    @user1406186 Additionally, the next time you ask on StackOverflow, please tell us what you tried. This question doesn't show any attempt to actually solve the problem. Show us what you tried and what error occurred. That way, it's way easier for people to help you and for future visitors to understand your problem. – Lukas Kalbertodt Apr 13 '19 at 09:28

1 Answers1

4

You can't. As of Rust 1.34.0, there is no function marked with const for BTreeMap. That's why you can't define a const BtreeMap at all.

The only way would be a static variable and the usage of the 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()
    };
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
hellow
  • 12,430
  • 7
  • 56
  • 79