【问题标题】:Cannot add a value other than a string to a nested hashmap无法将字符串以外的值添加到嵌套哈希图中
【发布时间】:2018-03-13 07:34:20
【问题描述】:

我想创建一个带有嵌套结构的HashMap,就像这个复杂的例子:

{
   type: boy
   name: Phineas
   father:
       type: man
       name: Lawrence
}

在 Rust 中,这将是:

use std::collections::HashMap;

let mut lawrence = HashMap::new();
lawrence.insert("type", "man");
lawrence.insert("name", "Lawrence");
let mut phineas = HashMap::new();
phineas.insert("type", "boy");
phineas.insert("name", "Phineas");
phineas.insert("father", lawrence);

但HashMap 的值似乎只能是字符串;如果我尝试编译,我会得到:

expected &str, found struct `std::collections::HashMap`

我查看了文档,但找不到构建类似数据结构的简单解决方案。

【问题讨论】:

  • phineas.insert("father", lawrence); 你的意思是“劳伦斯”吗?否则你的问题是,你不能将两种不同的类型插入到同一个哈希图中

标签: hashmap rust


【解决方案1】:

我假设您来自动态类型语言。在这种情况下,你真的需要通读Rust Book,因为Rust是一个非常不同的野兽。 Rust 是静态类型的,所以你在这里尝试做的几乎是行不通的,而且绝对不是你打算使用该语言的方式。

在这种特殊情况下,没有简单的答案,因为我不知道您的目标是什么。 Rust 中的数据结构建模是通过 structs、enums、Vec 和 HashMap 等集合、Option 等实用程序类型以及 Box、@987654330 等各种指针类型的组合来完成的@、等等。你需要什么具体的组合取决于你想要表达什么,你打算如何构建它,以及你打算如何使用它。

一个可能的表述是:

struct Person {
    kind: PersonKind,
    name: String,
    father: Option<Box<Person>>,
}

enum PersonKind {
    Boy,
    Man,
}

【讨论】:

  • 是的,我来自动态语言;我知道我在这里犯了一个菜鸟错误;谢谢指点!
【解决方案2】:

HashMap 是通用的。当您第一次插入时,编译器会确定类型并且不会让您使用其他类型。

pub struct HashMap<K, V, S = RandomState> { /* fields omitted */ }

pub fn insert(&mut self, k: K, v: V) -> Option<V>

V 是您的值的类型,K 是键的类型。由于 Rust 具有静态类型系统,因此必须考虑这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2016-09-06
    • 2012-08-07
    • 1970-01-01
    • 2017-05-26
    相关资源
    最近更新 更多