将 HashMap 编码为 bson 时 InvalidMapKeyType
InvalidMapKeyType when encoding a HashMap to bson
我想使用 bson::to_bson()
对 HashMap<u64, usize>
进行编码,以便将其存储在 MongoDB 中。
当我 运行 代码时,它惊慌并告诉我 InvalidMapKeyType(FloatingPoint(....))
。不能用这个方法把HashMap编码成这样的类型吗?
BSON library disallows all keys that are not strings. The BSON spec表示一个文档是一个元素序列,每个元素前面必须有一个名字,名字只能是一个字符串。
将您的 HashMap
更改为使用字符串作为键应该可以解决问题。
你的问题对我来说没有任何意义。您声明您有一个 HashMap<u64, usize>
但您的错误代码段指出这是因为 FloatingPoint
!
这就是为什么您应该始终创建一个 MCVE 然后在提问时提供它的原因。我创建了这个完全按照你所说的做的示例,但我得到了一个不同的错误:
extern crate bson; // 0.8.0
use std::collections::HashMap;
fn main() {
let mut thing = HashMap::new();
thing.insert(0_u64, 1_usize);
match bson::to_bson(&thing) {
Ok(e) => println!("{:?}", e),
Err(e) => println!("Got an error: {:?}, {}", e, e),
}
}
Got an error: UnsupportedUnsignedType, BSON does not support unsigned type
如果我将 HashMap
更改为带符号的数字,则会得到相同的 class 错误:
thing.insert(0_i64, 1_isize);
Got an error: InvalidMapKeyType(I64(0)), Invalid map key type: I64(0)
你甚至不能使用 f64
作为 Rust 中的键来创建 HashMap
,因为它没有实现 Hash
或 Eq
,所以我有不知道你是怎么得到那个特定错误的。
我想使用 bson::to_bson()
对 HashMap<u64, usize>
进行编码,以便将其存储在 MongoDB 中。
当我 运行 代码时,它惊慌并告诉我 InvalidMapKeyType(FloatingPoint(....))
。不能用这个方法把HashMap编码成这样的类型吗?
BSON library disallows all keys that are not strings. The BSON spec表示一个文档是一个元素序列,每个元素前面必须有一个名字,名字只能是一个字符串。
将您的 HashMap
更改为使用字符串作为键应该可以解决问题。
你的问题对我来说没有任何意义。您声明您有一个 HashMap<u64, usize>
但您的错误代码段指出这是因为 FloatingPoint
!
这就是为什么您应该始终创建一个 MCVE 然后在提问时提供它的原因。我创建了这个完全按照你所说的做的示例,但我得到了一个不同的错误:
extern crate bson; // 0.8.0
use std::collections::HashMap;
fn main() {
let mut thing = HashMap::new();
thing.insert(0_u64, 1_usize);
match bson::to_bson(&thing) {
Ok(e) => println!("{:?}", e),
Err(e) => println!("Got an error: {:?}, {}", e, e),
}
}
Got an error: UnsupportedUnsignedType, BSON does not support unsigned type
如果我将 HashMap
更改为带符号的数字,则会得到相同的 class 错误:
thing.insert(0_i64, 1_isize);
Got an error: InvalidMapKeyType(I64(0)), Invalid map key type: I64(0)
你甚至不能使用 f64
作为 Rust 中的键来创建 HashMap
,因为它没有实现 Hash
或 Eq
,所以我有不知道你是怎么得到那个特定错误的。