-2

I am new and lost in Rust a bit.

I would like to add keys and values to a data store that has a put function that takes two byte string literals:

batch.put(b"foxi", b"maxi");

I generate a bunch of these k-v pairs:

for _ in 1..1000000 {
    let mut ivec = Vec::new();
    let s1: u8 = rng.gen();
    let s2: u8 = rng.gen();
    ivec.push(s1);
    ivec.push(s2);
    debug!("Adding key: {} and value {}", s1, s2);
    vec.push(ivec);
}
let _ = database::write(db, vec);

I have a fn that tries to add them:

pub fn write(db: DB, vec: Vec<Vec<u8>>) {
    let batch = WriteBatch::new();
    for v in vec {
        batch.put(v[0], v[1]);
    }
    db.write(&batch).unwrap();
}

When I try to compile this I get:

error[E0308]: mismatched types
  --> src/database.rs:17:19
   |
17 |         batch.put(v[0], v[1]);
   |                   ^^^^ expected &[u8], found u8
   |
   = note: expected type `&[u8]`
              found type `u8`

error[E0308]: mismatched types
  --> src/database.rs:17:25
   |
17 |         batch.put(v[0], v[1]);
   |                         ^^^^ expected &[u8], found u8
   |
   = note: expected type `&[u8]`
              found type `u8`

I was ping-ponging with the borrow checker for a while now but I could not get it working. What is the best way to have byte literal strings from u8s?

Istvan
  • 7,500
  • 9
  • 59
  • 109
  • 1
    Make them 1-element arrays (`[u8; 1]`) instead of bare `u8`s? I believe `rng.gen()` will work for arrays. – trent Apr 25 '19 at 23:27
  • 2
    I would like to see a [mcve] before trying to write a real answer, since we can't know the definitions of `database` or `WriteBatch`, for example. The [Rust Playground](https://play.rust-lang.org/) is a good place to start -- if you can reproduce your error there with a minimal example, it would help a lot. – trent Apr 25 '19 at 23:33
  • 2
    Or maybe just `batch.put(&v[..1], &v[1..])` would work. – trent Apr 25 '19 at 23:38
  • `batch.put(&v[0..1], &v[1..2]);` or `batch.put(core::slice::from_ref(&v[0]), core::slice::from_ref(&v[1]));` – Chai T. Rex Aug 12 '22 at 17:42

1 Answers1

0

The following works:

batch.put(&v[0].as_bytes(), &v[1].as_bytes())
Istvan
  • 7,500
  • 9
  • 59
  • 109