【问题标题】:Having problems making a hashMap, can't understand error, full example制作 hashMap 时遇到问题,无法理解错误,完整示例
【发布时间】:2021-12-13 06:19:07
【问题描述】:

认为这很简单。

只想创建一个哈希映射,其中键是一个元组 (u8, &str),表示一组有序问题的数量,而字符串文字表示问题本身。然后值将是另一个元组 (&str, [&str;4]) 代表正确的字母和可能的答案

const ANSWER_KEY: HashMap<(u8, &str), (&str, [&str;4])> = HashMap::from {
    (1, "What is a programming language?") : ("B", [
        "A. A language that improves programming.",
        "B. A human readable language for humans that translates to a binary language to communicate with computers.",
        "C. A language read by computers that translates to a unary language to communicate with humans.",
        "D. A language created by Alan Turing.")
    ]
};

错误信息是:"What is a programmi...' unexpected&lt;struct literal field&gt; expected, got '('

【问题讨论】:

  • HashMap::from { key: value, ... } 语法无效。也许你想要HashMap::from([(key, value), ...]) 就像这个答案:stackoverflow.com/a/69640610/2189130
  • 谢谢你是def。一个错误但虽然现在错误是mismatched types [E0308] expected [((u8, &str), (&str, [&str; 4])); ], found (i32, &str)` `
  • 另外,如果问答是有序和编号的,为什么还要使用哈希图? Vec 不是更合适吗?
  • @kmdreko 是的,元组的 vec 听起来更合适

标签: rust


【解决方案1】:

你可以这样声明:

let answer: HashMap<(u8, &str), (&str, [&str;4])> = HashMap::from(
[
    ((1, "What is a programming language?"), ("B", [
    "A. A language that improves programming.",
    "B. A human readable language for humans that translates to a binary language to communicate with computers.",
    "C. A language read by computers that translates to a unary language to communicate with humans.",
    "D. A language created by Alan Turing."]))
]); 

由于错误 [E0015],您无法声明 const:常量中的调用仅限于常量函数、元组结构和元组变体

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 2018-11-24
    • 2020-02-27
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多