首页 > 解决方案 > 朱莉娅亚型逻辑对我没有任何意义

问题描述

我在子类型上使用地图,但它似乎不起作用,我总是收到错误消息。我的代码有什么问题,或者只是我错误地使用了 map 函数。我无法真正了解 Julia 中的类型、子类型和构造函数逻辑。提前感谢

abstract type AbstractModel end


function validator(::Type{T}) where {T<:AbstractModel}
     #fieldtype(T,1)<:Type ||error("Validation error for type of default"," in the Type $T accure the error") 
     fieldtype(T,3)<:String ||error("Validation error for type of default"," in the Type $T accure the error"  )
     fieldtype(T,4)<:Int||error("Validation error for type of default"," in the Type $T accure the error"  ) 
     fieldtype(T,5)<:Int ||error("Validation error for type of default"," in the Type $T accure the error"  ) 
end

struct Field5 <:AbstractModel
    type
    default
    description
    min
    max
    Field5(type,default,description,min,max)=new("","","this is descriptio",7,10)
end

map(validator, subtypes(AbstractModel))

标签: juliasubtypemapping

解决方案


看起来您只想提供事先不知道的字段类型并限制这些类型,您可以使用参数来做到这一点:

struct Field5{A<:Type,
              B<:Any,
              C<:String, 
              D<:Int,
              E<:Int}
    type::A
    default::B
    description::C
    min::D
    max::E
end

x1 = Field5(Float64,"b","c",7,10) # works
x2 = Field5(Float64,"b","c",7,1.0) # MethodError because 1.0 is not <: Int

或者,如果您不想限制类型而只使用 进行检查validator,那么您可以这样做:

struct Field5{A,B,C,D,E}
    type::A
    default::B
    description::C
    min::D
    max::E
end

function validator(::Type{T}) where {T<:Field5}
     fieldtype(T,1)<:Type ||error("Validation error for type of default"," in the Type $T accure the error") 
     fieldtype(T,3)<:String ||error("Validation error for type of default"," in the Type $T accure the error"  )
     fieldtype(T,4)<:Int||error("Validation error for type of default"," in the Type $T accure the error"  ) 
     fieldtype(T,5)<:Int ||error("Validation error for type of default"," in the Type $T accure the error"  ) 
end

x1 = Field5(Float64,"b","c",7,10) # works
x2 = Field5(Float64,"b","c",7,1.0) # works

# note that x1 and x2 have different concrete types; Field5 is abstract
# now validator can tell if a concrete type fits its criteria

validator(typeof(x1)) # true
validator(typeof(x2)) # Validation error because 1.0 is not <:Int

推荐阅读