Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array.new(size) error #7723

Closed
x-ror opened this issue Apr 27, 2019 · 4 comments
Closed

Array.new(size) error #7723

x-ror opened this issue Apr 27, 2019 · 4 comments

Comments

@x-ror
Copy link

x-ror commented Apr 27, 2019

I get error message when tring to initialize array in initialize method. i`m new in crystal, but i think it should works..
https://crystal-lang.org/api/0.28.0/Array.html#new%28size%3AInt%2C%26block%3AInt32-%3ET%29-class-method

abstract class ClassA
  @prev : UInt32
  @current : UInt32

  def initialize(@current : UInt32, @prev : UInt32)
    @weight = Array.new(3) { |i| (i + 1) ** 2 } # not works**
    weight2 = Array.new(3) { |i| (i + 1) ** 2 } # not works**
  end

  def some_func
    weight3 = Array.new(3) { |i| (i + 1) ** 2 } # works !**
  end
end
cast from Nil to Crystal::GenericInstanceType+ failed, at /crystal/src/compiler/crystal/types.cr:1651:20:1651 (TypeCastError)
  from ???
  from ???
  from ???
  from ???
  from ???
  from ???
  from ???
  from ???
  from ???
  from ???
  from ???
  from ???
  from ???
@x-ror
Copy link
Author

x-ror commented Apr 27, 2019

And why i can`t initialize array in this way @w = uninitialized Float64[@current]?

It works only when i pass number @w = uninitialized Float64[5]

@konovod
Copy link
Contributor

konovod commented Apr 27, 2019

For a first problem: only the first line don't works. This is because compiler must deduce type of @weight instance variable, and apparently it's not clever enough to find correct generic specialzation. Use Array(Int32).new ....
Second problem - uninitialized Float64[5] creates StaticArray - they are quite different from usual Array and must have fixed size (because they are allocated on stack).

@asterite
Copy link
Member

Duplicate of #6390

Also, never user uninitialized and never recommend it, please.

@asterite
Copy link
Member

As a workaround explicitly define the type of each instance variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants