如何将任何哈希添加到空的哈希数组?
how to add any hash to empty array of hashes?
我刚学 Crystal,但卡在混合类型哈希数组上。
假设有一个哈希数组:
array = [{"a" => "Aa", "b" => 66, "c" => Time.now}]
我可以轻松添加另一个元素:
array << {"c" => "Bb", "d" => 2, "f" => 1.year.from_now}
但是当我从空数组开始时:
empty = [] of Hash(String, String | Time | Int64)
尝试添加新元素,出现错误:
empty << {"a" => "Aa", "b" => 66, "c" => Time.now}
# no overload matches 'Array(Hash(String, Int64 | String | Time))#<<'
# with type Hash(String, Int32 | String | Time)
你能解释一下我做错了什么吗?
Link 到 sample code
你有点误会。您使用 String, Int64 | String | Time
定义了散列,但尝试使用 String, Int32 | String | Time
.
添加散列
只需将 Int64
更改为 Int32
即可,请参阅固定示例 — https://play.crystal-lang.org/#/r/6185
我刚学 Crystal,但卡在混合类型哈希数组上。
假设有一个哈希数组:
array = [{"a" => "Aa", "b" => 66, "c" => Time.now}]
我可以轻松添加另一个元素:
array << {"c" => "Bb", "d" => 2, "f" => 1.year.from_now}
但是当我从空数组开始时:
empty = [] of Hash(String, String | Time | Int64)
尝试添加新元素,出现错误:
empty << {"a" => "Aa", "b" => 66, "c" => Time.now}
# no overload matches 'Array(Hash(String, Int64 | String | Time))#<<'
# with type Hash(String, Int32 | String | Time)
你能解释一下我做错了什么吗?
Link 到 sample code
你有点误会。您使用 String, Int64 | String | Time
定义了散列,但尝试使用 String, Int32 | String | Time
.
只需将 Int64
更改为 Int32
即可,请参阅固定示例 — https://play.crystal-lang.org/#/r/6185