Is there any optimization for constants?

The issue is caused by a bug, so we could try to fix it (Multiple initializations of a constant when using pointerof() · Issue #13054 · crystal-lang/crystal · GitHub).

Until then as a workaround you can declare the class variable with uninitialized and assign a value from within a method (a proc would work as well).

class Foo
  @@foo = uninitialized Int32

  init_foo
  def self.init_foo
    @@foo = begin
      puts "Initializing Foo"
      1
    end
  end
  
  pointerof(@@foo)
end

Maybe there’s an easier solution, but this works :person_shrugging:

2 Likes