gpt4 book ai didi

crystal-lang - 嵌套哈希生成错误

转载 作者:行者123 更新时间:2023-12-01 01:48:42 25 4
gpt4 key购买 nike

鉴于以下代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com