定义一个空Dict,其中值是抽象类型的子类型

问题描述

我有一个带有子类型的抽象类型。 我想制作并添加到一个包含子类型的Dict。 这可行吗? 有什么更好的方法来实现这一目标?

示例:

abstract type Cat end

struct Lion <: Cat
   manecolour
end

struct Tiger <: Cat
   stripewidth
end

cats = Dict{Int,<:Cat}()

给予

ERROR: MethodError: no method matching Dict{Int64,var"#s3"} where var"#s3"<:Cat()

更正确的方法是什么?

解决方法

只需将抽象类型用作容器类型:final static int nbBytesInFloat = Float.SIZE / Byte.SIZE; public static byte[] toByteArray(float[] floatArray){ byte[] result = new byte[floatArray.length * nbBytesInFloat]; ByteBuffer wrappedBytes = ByteBuffer.wrap(result); for(int i=0;i<floatArray.length;i++) { wrappedBytes.putFloat(floatArray[i]); } return result; } public static float[] toFloatArray(byte[] byteArray){ ByteBuffer buffer = ByteBuffer.wrap(byteArray); float[] result = new float[byteArray.length / nbBytesInFloat]; for(int i=0;i<result.length;i++) { result[i] = buffer.getFloat(); } return result; }

cats = Dict{Int,Cat}()
,

类型为DataType-类型UnionAll除外。所以你可以做

julia> d = Dict{Int,Union{DataType,UnionAll}}()
 Dict{Int64,UnionAll}}()

julia> for (i,type) in enumerate(subtypes(Integer))
           d[i] = type
       end

julia> d
 Dict{Int64,UnionAll}} with 3 entries:
  2 => Signed
  3 => Unsigned
  1 => Bool
,

如果Cat类型的数量很少,则可以避免使用抽象容器来提高性能:

cats = Dict{Int,Cat}()
cats[1] = Lion(12)

cats2 = Dict{Int,Union{subtypes(Cat)...}}()
cats2[1] = Lion(12)

现在进行测试(我正在使用TigerLion猫类型):

julia> @btime $cats[1].manecolour == 12;
  25.300 ns (0 allocations: 0 bytes)

julia> @btime $cats2[1].manecolour == 12;
  17.434 ns (0 allocations: 0 bytes)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...