Curly Brace Designs?

While reading through Crystal docs, I came across this line:

deq = Deque{2, 3} 

So, I think this calls the constructor Deque.new(array : Array(T)) . However, I did not find any documentation about this syntax. ( EDIT : Documentation can be found here )

To test this way of calling constructors, I wrote the following test

 class Foo(T) def initialize(@bar : Array(T)); end def to_s(io : IO) io << "Foo: " io << @bar end end puts Foo{1} # Line 10 

But when compiling, it prints this error:

 Error in line 10: wrong number of arguments for 'Foo(Int32).new' (given 0, expected 1) Overloads are: - Foo(T).new(bar : Array(T)) 

What I really don't understand. Foo(Int32){1} Raises the same error.

The question is, what is the syntax of Klass{1, 2, 3} ? And how do you use it?

+5
source share
2 answers

They are described here: https://crystal-lang.org/docs/syntax_and_semantics/literals/array.html


An array of type Literal

Crystal supports an extra literal for arrays and array types. It consists of a type name, followed by a list of elements enclosed in braces ( {} ), and individual elements separated by a comma ( , ).

 Array{1, 2, 3} 

This literal can be used with any type if it has a constructor without arguments and responds with << .

 IO::Memory{1, 2, 3} Set{1, 2, 3} 

For a non-generic type like IO::Memory this is equivalent to:

 array_like = IO::Memory.new array_like << 1 array_like << 2 array_like << 3 

For a type such as Set , the generic type T is inferred from element types in the same way as with an array literal. The above is equivalent to:

 array_like = Set(typeof(1, 2, 3)).new array_like << 1 array_like << 2 array_like << 3 

Type arguments can be explicitly specified as part of the type name:

 Set(Number) {1, 2, 3} 
+7
source

To create this type, you need to define a constructor with no arguments and the #<< method:

 class Foo(T) def initialize @store = Array(T).new end def <<(elem : T) @store << elem end end foo = Foo(Int32){1, 2, 3} p foo #=> #<Foo(Int32):0x103440b20 @store=[1, 2, 3]> 
+3
source

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


All Articles