How do you create BTreeMap with byte arrays?

Just start (try) learning Rust. How can I use "bytestrings" as keys in std :: collections :: BTreeMap?

It looks like I can't use [u8] because the type requires a fixed size.

Using vectors like

BTreeMap<Vec<u8>, MyType>

      

... seems wasteful.

I could try to concatenate all bytes into one Vec and use chunks of that as BTree keys, but is there a better way to do this?

+3


source to share


1 answer


use std::collections::BTreeMap;

fn main() {
    let key1 = b"1234";
    let key2 = b"5678";

    let mut map = BTreeMap::new();

    map.insert(key1, true);
    map.insert(key2, false);

    println!("{}", map);
}

      



As you saw, it [u8]

is a type that does not have any size, which means that you cannot store them somewhere. Instead, you will want to store the "u8s chunk" recorded &[u8]

as a key. In this example, I just created a few discardable fragments, but yours will most likely be created from some owner object.

+1


source







All Articles