设置类型 "Class" 的属性以将其定义为 Int32、String、Float64
Set attribute of type "Class" to define it as Int32, String, Float64
我有一个 class Container
,它有一个属性 type
存储其中存储的元素类型:
class Container
def initialize(@type = Class)
end
end
我想这样使用它:
array = Container.new(Int32)
# or
array = Container.new(String)
然而,当 运行 我得到:can't use Class as the type of instance variable @dtype of Crystalla::Ndarray, use a more specific type
我怎样才能做到这一点?
如果我查看其他语言和库,例如 numpy,它们会在它们的 ndarrays 中存储一个类型:
np.ndarray(shape=(2,2), dtype=float)
我怎样才能在 crystal 中实现类似的东西?
编辑:dtype 在 python 中是一个 class 本身,但它似乎仍然保持 type/class 就像我试图实现
我认为你应该为此使用泛型。
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
,因为您总是可以在class定义中引用T
类型。
我有一个 class Container
,它有一个属性 type
存储其中存储的元素类型:
class Container
def initialize(@type = Class)
end
end
我想这样使用它:
array = Container.new(Int32)
# or
array = Container.new(String)
然而,当 运行 我得到:can't use Class as the type of instance variable @dtype of Crystalla::Ndarray, use a more specific type
我怎样才能做到这一点? 如果我查看其他语言和库,例如 numpy,它们会在它们的 ndarrays 中存储一个类型:
np.ndarray(shape=(2,2), dtype=float)
我怎样才能在 crystal 中实现类似的东西?
编辑:dtype 在 python 中是一个 class 本身,但它似乎仍然保持 type/class 就像我试图实现
我认为你应该为此使用泛型。
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
,因为您总是可以在class定义中引用T
类型。