我正在尝试对数据进行编码,然后将其存储在leveldb中,然后对其进行读取和解码,但是当我尝试进行解码并且确实不知道如何解决此错误时出现错误InvalidTagEncoding(usize)] >:如果反序列化器尝试反序列化不在预期范围内的枚举的标签,则返回此参数][dependencies]
serde = { version = "1.0.101", features = ["derive"] }
bincode = "1.2.0"
leveldb = "0.8.4"
main.rs
extern crate bincode; use leveldb::database::Database; use leveldb::kv::KV; use leveldb::options::{Options, ReadOptions, WriteOptions}; use std::path::Path; fn main() { // Encode data let encoded: Vec<u8> = bincode::serialize(&String::from("This is some data")).unwrap(); // Open database let mut options = Options::new(); options.create_if_missing = true; let path = Path::new("./db"); let database = match Database::open(&path, options) { Ok(db) => db, Err(e) => panic!("failed to open database: {:?}", e), }; // Write encoded data into database let write_opts = WriteOptions::new(); match database.put(write_opts, 1, &encoded) { Ok(_) => (), Err(e) => panic!("failed to write to database: {:?}", e), }; // Read encoded data from the database let read_opts = ReadOptions::new(); let res = database.get(read_opts, 1); match res { Ok(data) => { println!("the bytecode is {:?}", data); match data { Some(inner) => { let decoded: Option<String> = bincode::deserialize(&inner[..]).unwrap(); // ERROR println!("{:?}", decoded); }, None => println!("None 2"), } } Err(e) => panic!("failed reading data: {:?}", e), } }
输出
the bytecode is Some([17, 0, 0, 0, 0, 0, 0, 0, 84, 104, 105, 115, 32, 105, 115, 32, 115, 111, 109, 101, 32, 100, 97, 116, 97]) thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: InvalidTagEncoding(17)', src/libcore/result.rs:999:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
我正在尝试对数据进行编码,然后将其存储在leveldb中,然后读取它并对其进行解码,但是当我尝试进行解码并且确实不知道如何解决此错误时,我得到了一个错误InvalidTagEncoding(...
如注释中的trentcl所指出,您正在编码String
,但尝试将其解码为Option<String>
。更改:
let decoded: Option<String> = bincode::deserialize(&inner[..]).unwrap(); // ERROR