julia - 朱莉娅亚型逻辑对我没有任何意义
问题描述
我在子类型上使用地图,但它似乎不起作用,我总是收到错误消息。我的代码有什么问题,或者只是我错误地使用了 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))
解决方案
看起来您只想提供事先不知道的字段类型并限制这些类型,您可以使用参数来做到这一点:
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
推荐阅读
- flutter - 如何从颤振应用程序中投射屏幕?
- python - 如何使用线程更新 tkinter gui 标签?
- html - 如何使一端有滚动的模态框的角变圆
- flutter-provider - 在颤动中使用数据库提供者模式
- r - R 控制台和笔记本中的奇怪字符
- python - 如何使用 ReportLab 在 PDF 中绘制电子签名
- openwhisk - OpenWhisk 是否支持 OpenAPI 3.x 规范?
- css - 使用 Jekyll / Hugo 站点的自托管 Nginx 未加载 CSS
- google-apps-script - 添加 OAUTH 范围时如何不执行“onAddToSpace”
- swift - 为什么具有 autosaveExpandedItems true 的基于视图的 NSOutlineView 在 reloadData 时忽略扩展?