如何解决定义一个空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)
现在进行测试(我正在使用Tiger
和Lion
猫类型):
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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。