设置类型" Class"的属性将其定义为Int32,String,Float64

时间:2016-12-22 19:06:50

标签: crystal-lang

我有一个类<div></div> <div></div> <div></div>,它有一个属性Container,用于存储存储在其中的元素类型:

type

我想这样使用它:

class Container

  def initialize(@type = Class) 

  end

end

然而,在运行时,我得到:array = Container.new(Int32) # or array = Container.new(String)

我怎样才能做到这一点? 如果我看看其他语言和像numpy这样的库,他们会在他们的ndarrays中存储一个类型:

can't use Class as the type of instance variable @dtype of Crystalla::Ndarray, use a more specific type

我怎样才能在水晶中实现类似的东西?

编辑:dtype本身就是python中的一个类,但它似乎仍然拥有类似于我试图实现的类型/类

1 个答案:

答案 0 :(得分:2)

我认为你应该使用泛型。

class Container(T)
  @type : T.class
  @array : Array(T)

  def initialize
    @array = Array(T).new
    @type = T

    puts "Container elements type is #{@type}"
  end
end

array = Container(Int32).new

当然可以删除实例变量@type,因为您始终可以在类定义中引用T类型。