鉴于以下代码:
require "big"
alias Type = Nil | String | Bool | Int32 | BigFloat | Array(Type) | Hash(String | Symbol, Type)
alias HOpts = Hash(String | Symbol, Type)
ctx = HOpts.new
ctx["test_int"] = 1
ctx["test_s"] = "hello"
c1 = Hash(String, Type).new
ctx["stuff"] = c1
ctx["stuff"]["foo"] = { "bar" => 1 }
我得到:
Error in test.cr:13: instantiating 'Hash(String | Symbol, Type)#[]=(String, Hash(String, Type))'
ctx["stuff"] = c1
^
in /opt/crystal/src/hash.cr:43: instantiating 'insert_in_bucket(Int32, String, Hash(String, Type))'
entry = insert_in_bucket index, key, value
^~~~~~~~~~~~~~~~
in /opt/crystal/src/hash.cr:842: instantiating 'Hash::Entry(String | Symbol, Type)#value=(Hash(String, Type))'
entry.value = value
^~~~~
in /opt/crystal/src/hash.cr:881: expanding macro
property value : V
^
in macro 'property' expanded macro: macro_83313872:567, line 10:
1.
2.
3.
4. @value : V
5.
6. def value : V
7. @value
8. end
9.
> 10. def value=(@value : V)
11. end
12.
13.
14.
15.
instance variable '@value' of Hash::Entry(String | Symbol, Type) must be Type, not Hash(String, Type)
我希望能够创建任何类型的嵌套哈希,但它不起作用。
最佳答案
这里有一些问题。c1
的类型是 Hash(String, Type)
这不是 Type
的类型之一联盟。 Hash(String, Type)
与 Hash(String | Symbol, Type)
不兼容.
要么包括 Hash(String, Type)
在 Type
联合,或给 c1
型号 Hash(String | Symbol, Type)
(即 HOpts
):
c1 = HOpts.new
这行代码还会出现另一个错误:
ctx["stuff"]["foo"] = { "bar" => 1 }
ctx["stuff"]
将返回 Type
类型的对象而不是你期望的哈希值。如果您确定知道 ctx["stuff"]
是一个散列(我们从这个例子中做的)那么你需要限制它的类型。还有 { "bar" => 1 }
类型为 Hash(String, Int32)
而不是 Hash(String, Type)
,所以你也需要指定这个:ctx["stuff"].as(HOpts)["foo"] = HOpts{ "bar" => 1 }
关于crystal-lang - 嵌套哈希生成错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46262958/