Julia 结构体与类型系统
用采样记录核对字段类型、可变性、参数不变性、构造器和枚举。
学完这一章,你能够
- 用采样记录核对字段类型、可变性、参数不变性、构造器和枚举。
字段、构造和修改
struct 组合若干字段,字段可声明不同类型。省略字段类型时使用 Any。默认构造器按声明转换兼容输入,例如 7.0 可以进入 Int 字段,7.5 会抛 InexactError。类型名可调用,实例以点号访问字段。
不可变结构体的字段不能改绑,其中若保存向量,仍可修改那个向量。=== 的结果取决于内容和所含对象的身份,不能用打印相同的内容推断身份。标量不可变值常可按内容区分,编译器是否省掉分配由具体情形决定。
mutable struct 允许改绑普通字段。Julia 1.8 起可给其中字段加 const。自定义 == 可比较内容,=== 仍区分两个独立的可变实例。若要把自定义值用作字典键,还应让 isequal 与 hash 的规则相容。
抽象类型、联合和参数化
abstract type 描述类型层级,不能直接构造实例。Number 包含复数和实数家族,Real 下有整数、浮点、有理数等。<: 检查子类型关系,supertype 与 subtypes 分别观察直接上级和当前已加载的直接下级。
struct PairOf{T} 的两个字段可以同由 T 决定。默认外层构造器可从同类型参数推断 T,混合类型时可显式给类型参数或另写转换。T<:Real 限制类型参数;没有适用方法和指定非法类型参数属于两类错误。
Vector{Int} 不是 Vector{Real} 的子类型,即使 Int <: Real。希望覆盖多种实数元素类型,可以写 Vector{<:Real}。Union{Int,Nothing} 允许计数或无值;Nothing 和 Missing 对应不同语义。
构造器和枚举
外部构造器可给默认值并调用其它构造方法。内部构造器在类型体内用 new 创造对象,适合维护不变量。定义内部构造器后,由它们决定实例创建条件,不再自动给出默认内部构造器。
@enum 可以从零分配枚举值,也可给首个成员明确指定整数。构造器可按合法整数取得枚举值,非法编号会报错。Int(member) 取得成员编号。
查询与判断类型
| 接口 | 用途 |
|---|---|
| typeof(x) | 返回值的具体类型。 |
| isa(x, T) | 测试值 x 是否属于 T 所描述的类型。 |
| T1 <: T2 | 判断左类型是否为右类型的子类型。 |
| supertype(T) | 查询类型的直接父类型。 |
| subtypes(T) | InteractiveUtils 接口,返回当前已加载的直接子类型。 |
| fieldnames(T) | 返回结构体字段名元组。 |
| fieldtypes(T) | 返回结构体字段的声明类型元组。 |
| Union{T1, T2} | 值属于两个类型中的至少一个即可。 |
| Union{} | 空类型,没有实例,是所有类型的子类型。 |
| Nothing / nothing | Nothing 的唯一实例是 nothing,用于表示无值。 |
类型实例:字段转换、不变量与对象身份
using InteractiveUtils
include(joinpath(@__DIR__, "observations.jl"))
struct Station
x::Int
y::Float64
label
end
s=Station(7.0,11,:bay)
probe("struct_construct",(7.0,11,:bay),(typeof(s),s.x,s.y,s.label,fieldtypes(Station),
outcome(() -> Station(7.5,11,:bay)),typeof(Station(7,11,"bay").label)),
(Station,7,11.0,:bay,(Int,Float64,Any),"InexactError",String))
probe("struct_immutable",s,(isimmutable(s),outcome(() -> setproperty!(s,:x,9))), (true,"ErrorException"))
struct Position
x::Int
y::Int
end
struct Payload
samples::Vector{Int}
end
shared=[7]
a,b=Payload(shared),Payload(shared)
c=Payload([7])
push!(a.samples,11)
probe("struct_immutable_identity","two scalar records; same and distinct inner vectors",
(Position(7,11)===Position(7,11),a===b,a===c,b.samples,c.samples),
(true,true,false,[7,11],[7]))
mutable struct StationStack
values::Vector{Any}
label::String
end
q=StationStack(Any[],"incoming")
push!(q.values,7)
q.label="reviewed"
probe("struct_mutable",("incoming",7,"reviewed"),(q.values,q.label,isimmutable(q)),(Any[7],"reviewed",false))
left=StationStack(Any[7],"north")
right=StationStack(Any[7],"north")
default_equal=(left===right,left==right)
Base.:(==)(a::StationStack,b::StationStack)=a.label==b.label && a.values==b.values
probe("struct_value_equality","equal content in two mutable instances",(default_equal,left==right,left===right),
((false,false),true,false))
mutable struct Sensor
reading::Int
const calibration::Float64
end
sensor=Sensor(7,1.5)
sensor.reading=11
probe("struct_const", (7,1.5,11),(sensor.reading,sensor.calibration,
outcome(() -> setproperty!(sensor,:calibration,3.0))),(11,1.5,"ErrorException"))
abstract type Reading end
abstract type NumericReading <: Reading end
struct CountReading <: NumericReading
value::Int
end
probe("struct_abstract",Reading,(NumericReading<:Reading,isabstracttype(Reading),
outcome(() -> Reading()),CountReading(7) isa Reading),
(true,true,"MethodError",true))
probe("struct_number_tree","selected numeric families",
(Complex{Int}<:Number,Integer<:Real,Int<:AbstractFloat,Float64<:AbstractFloat,BigFloat<:AbstractFloat,
Bool<:Integer,BigInt<:Signed,UInt16<:Unsigned,Rational{Int}<:Real,typeof(pi)<:Real,Any<:Any),
(true,true,false,true,true,true,true,true,true,true,true))
struct PairOf{T}
first::T
last::T
end
probe("struct_parameter",(7,11,7.0,11.0),(typeof(PairOf(7,11)),typeof(PairOf(7.0,11.0)),
outcome(() -> PairOf(7,11.0)),PairOf{Float64}(7,11).first),
(PairOf{Int},PairOf{Float64},"MethodError",7.0))
struct RealPair{T<:Real}
first::T
last::T
end
probe("struct_bounded_parameter",(7,"north"),(typeof(RealPair(7,11)),
outcome(() -> RealPair(7,"north")),outcome(() -> RealPair{String}("a","b"))),
(RealPair{Int},"MethodError","TypeError"))
struct SampleBatch{T}
rows::Vector{T}
end
struct OptionalCount
value::Union{Int,Nothing}
end
probe("struct_container_union",([7,11],nothing),
(typeof(SampleBatch([7,11])),OptionalCount(7).value,OptionalCount(nothing).value),
(SampleBatch{Int},7,nothing))
probe("struct_invariance","Vector{Int} and abstract element types",
(Int<:Real,Vector{Int}<:Vector{Real},Vector{Int}<:Vector{<:Real}),(true,false,true))
struct Twin
a
b
end
Twin(x)=Twin(x,x)
struct BoundsPair
lower::Real
upper::Real
BoundsPair(lo,hi)=lo<=hi ? new(lo,hi) : throw(ArgumentError("upper bound below lower"))
end
pair=BoundsPair(7,11)
probe("struct_constructors",(7,11),(Twin(7).a,Twin(7).b,pair.lower,pair.upper,outcome(() -> BoundsPair(11,7))),
(7,7,7,11,"ArgumentError"))
@enum Signal Idle Running Paused
@enum Source North=4 South West
probe("struct_enum","default and explicit starting values",
(Int(Idle),Int(Paused),Int(North),Source(5),Int(West),outcome(() -> Source(100))),
(0,2,4,South,6,"ArgumentError"))
probe("struct_typeof",s,typeof(s),Station)
probe("struct_isa",7,(isa(7,Int),isa(7,Any),isa(7,Float64)),(true,true,false))
probe("struct_subtype",Int,(Int<:Integer,Int<:Real,Int<:AbstractFloat),(true,true,false))
probe("struct_supertype",Int,supertype(Int),Signed)
probe("struct_subtypes",Reading,sort!(string.(subtypes(Reading))),["NumericReading"])
probe("struct_fieldnames",Station,fieldnames(Station),(:x,:y,:label))
probe("struct_fieldtypes",Station,fieldtypes(Station),(Int,Float64,Any))
probe("struct_union",Union{Int,Nothing},(7 isa Union{Int,Nothing},nothing isa Union{Int,Nothing},
"north" isa Union{Int,Nothing}),(true,true,false))
probe("struct_bottom",Union{},(Union{}<:Int,Union{}<:Any,7 isa Union{}),(true,true,false))
probe("struct_nothing",nothing,(typeof(nothing),nothing===nothing,nothing===missing),(Nothing,true,false))
- 把 7.0 传给 Int 字段得到 7,把 7.5 传给同字段得到 InexactError。倒序边界构造抛 ArgumentError,默认枚举从 0 编号。
所需环境:Julia 1.10.13 官方便携版,Windows x64,本机隔离目录
当前源码 SHA256:fbae8c2644cb0281312830bedd11b4aa2d068e5d86bbaf957f71fc8c083cbe8b
本机练习工程
解压后分别执行两个脚本。练习只修改自己定义的类型或教学模块。
所需环境:Julia 1.10.13 官方便携版,Windows x64,本机隔离目录
ZIP SHA256:076c230015b28711d96f6ac9628944f4c7827173d21bc6fb95271cb4215f6a40
常见错误与边界
- 字段类型可各不相同。不能把某个固定字段的类型约束推广为所有字段同类型。
练习与解答
怎样让同一个结构体的两个字段各自独立推断类型?
展开参考解答
可以声明两个独立的类型参数,分别绑定字段。