参数化类型 #
一、基本语法 #
1.1 定义参数化类型 #
julia
struct Point{T}
x::T
y::T
end
1.2 创建实例 #
julia
p1 = Point(1.0, 2.0)
p2 = Point(1, 2)
p3 = Point{Float64}(1, 2)
typeof(p1)
typeof(p2)
typeof(p3)
1.3 类型参数 #
julia
Point{Float64}
Point{Int}
Point
二、类型参数约束 #
2.1 基本约束 #
julia
struct Point{T<:Real}
x::T
y::T
end
Point(1, 2)
Point(1.0, 2.0)
Point("a", "b")
2.2 多类型参数 #
julia
struct Pair{T, S}
first::T
second::S
end
p = Pair(1, "hello")
typeof(p)
2.3 复杂约束 #
julia
struct Matrix{T<:Number, N}
data::Array{T, N}
end
三、参数化抽象类型 #
3.1 定义 #
julia
abstract type AbstractArray{T, N} end
abstract type AbstractDict{K, V} end
3.2 继承 #
julia
struct MyArray{T, N} <: AbstractArray{T, N}
data::Array{T, N}
end
四、方法定义 #
4.1 参数化方法 #
julia
function add(p1::Point{T}, p2::Point{T}) where {T}
Point(p1.x + p2.x, p1.y + p2.y)
end
Point(1, 2) + Point(3, 4)
Point(1.0, 2.0) + Point(3.0, 4.0)
4.2 不同类型参数 #
julia
function add(p1::Point{T}, p2::Point{S}) where {T, S}
R = promote_type(T, S)
Point{R}(p1.x + p2.x, p1.y + p2.y)
end
Point(1, 2) + Point(3.0, 4.0)
4.3 类型参数方法 #
julia
function process(p::Point{Int})
"Integer point: $(p.x), $(p.y)"
end
function process(p::Point{Float64})
"Float point: $(p.x), $(p.y)"
end
process(Point(1, 2))
process(Point(1.0, 2.0))
五、类型族 #
5.1 同构类型族 #
julia
struct Vector3D{T}
x::T
y::T
z::T
end
Vector3D(1, 2, 3)
Vector3D(1.0, 2.0, 3.0)
5.2 异构类型族 #
julia
struct HeteroPair{T, S}
first::T
second::S
end
HeteroPair(1, "hello")
HeteroPair(1.0, 2)
六、实践练习 #
6.1 练习1:泛型栈 #
julia
mutable struct Stack{T}
data::Vector{T}
Stack{T}() where {T} = new{T}(T[])
end
function push!(s::Stack{T}, x::T) where {T}
push!(s.data, x)
end
function pop!(s::Stack{T}) where {T}
isempty(s.data) && error("Stack is empty")
pop!(s.data)
end
Base.isempty(s::Stack) = isempty(s.data)
Base.length(s::Stack) = length(s.data)
s = Stack{Int}()
push!(s, 1)
push!(s, 2)
push!(s, 3)
pop!(s)
6.2 练习2:泛型队列 #
julia
mutable struct Queue{T}
data::Vector{T}
Queue{T}() where {T} = new{T}(T[])
end
function enqueue!(q::Queue{T}, x::T) where {T}
push!(q.data, x)
end
function dequeue!(q::Queue{T}) where {T}
isempty(q.data) && error("Queue is empty")
popfirst!(q.data)
end
Base.isempty(q::Queue) = isempty(q.data)
Base.length(q::Queue) = length(q.data)
q = Queue{String}()
enqueue!(q, "first")
enqueue!(q, "second")
dequeue!(q)
6.3 练习3:泛型树 #
julia
struct TreeNode{T}
value::T
children::Vector{TreeNode{T}}
TreeNode{T}(value::T) where {T} = new{T}(value, TreeNode{T}[])
end
function add_child!(parent::TreeNode{T}, child::TreeNode{T}) where {T}
push!(parent.children, child)
end
root = TreeNode{Int}(1)
add_child!(root, TreeNode{Int}(2))
add_child!(root, TreeNode{Int}(3))
七、总结 #
本章我们学习了:
- 参数化类型定义:struct Point
- 类型参数约束:T <: Real
- 多类型参数:Pair
- 参数化抽象类型:抽象类型继承
- 参数化方法:where语法
接下来让我们学习Julia的类型注解!
最后更新:2026-03-27