Crystal: Initialization failure when in {% begin %} {% end %}

Created on 11 May 2019  路  2Comments  路  Source: crystal-lang/crystal

Instance variables initialized within {% begin %} {% end %} does not compile.

https://play.crystal-lang.org/#/r/6wbt

struct Foo
  @value : Int32

  def initialize
    {% begin %}
      @value = 5
    {% end %}
  end
end
Error in line 2: instance variable '@value' of Foo was not initialized directly in all of the 'initialize' methods, rendering it nilable. Indirect initialization is not supported.

All 2 comments

Not a bug, macros are analyzed on method instantiation. There's a similar bug report (which is not a bug to me) if you search something like initialize macro.

It looks like initialization in a macro is not possible without {{@type}}. So this will work:

struct Foo
  @value : Int32

  def initialize
    {{@type}}
    {% if true %}
      @value = 5
    {% end %}
  end
end

Playground

Was this page helpful?
0 / 5 - 0 ratings

Related issues

asterite picture asterite  路  3Comments

pbrusco picture pbrusco  路  3Comments

will picture will  路  3Comments

oprypin picture oprypin  路  3Comments

jhass picture jhass  路  3Comments