Nested hash generation error

Given the following code:

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 }

I get:

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)

I expect that I can create some kind of nested hash, but it does not work.

+4
source share
1 answer

Something is wrong there.

Type c1- Hash(String, Type)which is not one of the union types Type. Hash(String, Type)not compatible with Hash(String | Symbol, Type).

Either include Hash(String, Type)in the union Type, or give a c1type Hash(String | Symbol, Type)(i.e. HOpts):

c1 = HOpts.new

You will also have another error in this line of code:

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 }
+3

Source: https://habr.com/ru/post/1685822/


All Articles