Julia 数据类型全景图(中文版)
“一切皆类型” —— Julia 的类型系统是其高性能与灵活性的基石
一、Julia 类型系统概览
Any
├── Concrete Types(具体类型)
│ ├── Number
│ │ ├── Real
│ │ │ ├── Integer
│ │ │ │ ├── Bool
│ │ │ │ ├── Signed (Int8, Int16, Int32, Int64, Int128)
│ │ │ │ └── Unsigned (UInt8, UInt16, UInt32, UInt64, UInt128)
│ │ │ └── Rational & Float (Float16, Float32, Float64)
│ │ └── Complex
│ ├── AbstractArray{T, N}
│ ├── Tuple
│ ├── NamedTuple
│ ├── String
│ ├── Symbol
│ └── ...
└── Abstract Types(抽象类型)
核心原则:
- 具体类型(Concrete Type)才能实例化
- 抽象类型(Abstract Type)用于派发和分类
- 所有值都是某个具体类型的实例
二、核心内置类型详解
1. 数值类型(Number)
| 类型 | 说明 | 示例 |
|---|---|---|
Int64 | 默认整数(64 位) | 42 |
Float64 | 默认浮点(双精度) | 3.14 |
Bool | 布尔值 | true, false |
Complex | 复数 | 3 + 4im |
Rational | 有理数 | 2//3 |
typeof(42) # Int64
typeof(3.14) # Float64
typeof(3 + 4im) # Complex{Int64}
typeof(2//3) # Rational{Int64}
类型转换
convert(Float64, 42) # 42.0
Float64(42) # 42.0
Int(3.14) # 3(截断)
round(Int, 3.7) # 4
2. 字符串与字符
| 类型 | 说明 |
|---|---|
String | UTF-8 编码字符串 |
Char | 单个 Unicode 字符(单引号) |
s = "Julia 语言"
c = '中' # Char
codepoint(c) # 20013(Unicode 码点)
string('A', 'B') # "AB"
3. 数组(Array)—— 最重要容器
a = [1, 2, 3] # Vector{Int64}
m = [1 2; 3 4] # 2×2 Matrix{Int64}
Vector{T} = Array{T,1}Matrix{T} = Array{T,2}
eltype(a) # Int64
ndims(a) # 1
size(m) # (2, 2)
4. 元组(Tuple)与命名元组(NamedTuple)
t = (1, "hi", 3.14) # Tuple{Int64, String, Float64}
nt = (name="Julia", v=1.10) # NamedTuple{(:name, :v), Tuple{String, Float64}}
- 不可变
- 支持异构元素
- 命名元组支持
.name访问
5. 字典(Dict)与集合(Set)
d = Dict("a" => 1, "b" => 2) # Dict{String, Int64}
s = Set([1, 2, 2, 3]) # Set{Int64} with 3 elements
6. 符号(Symbol)
:name
Symbol("x") # :x
- 轻量级标识符
- 常用于键、宏、元编程
7. Nothing 与 Missing
nothing # 表示“无值”
missing # 表示缺失数据(常用于 DataFrames)
x = nothing
typeof(x) # Nothing
y = missing
ismissing(y) # true
三、类型层级查询
# 查看父类型
supertype(Int64) # Signed
supertype(Signed) # Integer
supertype(Integer) # Real
supertype(Real) # Number
supertype(Number) # Any
# 查看子类型
subtypes(Integer) # [Bool, Signed, Unsigned]
subtypes(AbstractArray) # [Array, BitArray, ...]
工具函数:
isa(x, T)→x isa Ttypeof(x)supertype(T),subtypes(T)
四、参数化类型(Parametric Types)
Vector{Int} # 元素为 Int 的向量
Dict{String, Float64}
Tuple{Int, String}
自定义参数化类型
struct Point{T}
x::T
y::T
end
p1 = Point(1, 2) # Point{Int64}
p2 = Point(1.0, 2.0) # Point{Float64}
五、联合类型(Union)
IntOrString = Union{Int, String}
x::IntOrString = 42
y::IntOrString = "hello"
常用于可选参数:
function f(x::Union{Int, Nothing})
x === nothing && return 0
return x^2
end
六、类型稳定性(Type Stability)—— 性能关键!
# 好:类型稳定
function sum_positive(v::Vector{Int})
s = 0
for x in v
x > 0 && (s += x)
end
return s::Int
end
# 坏:返回类型不确定
bad(x) = x > 0 ? x : "negative" # 返回 Int 或 String
检查方法:
@code_warntype f(args)
七、类型注解与声明
x::Int = 42
y::Float64 = 3.14
function add(a::Int, b::Int)::Int
return a + b
end
注解不影响运行,但:
- 提升性能(编译器优化)
- 提高代码可读性
- 便于静态分析
八、抽象类型 vs 具体类型
| 特性 | 抽象类型 | 具体类型 |
|---|---|---|
| 可实例化 | No | Yes |
| 可继承 | Yes | No |
| 性能 | 用于派发 | 最高性能 |
| 示例 | Number, AbstractArray | Int64, Vector{Int} |
abstract type Animal end
struct Dog <: Animal; name::String; end
struct Cat <: Animal; name::String; end
greet(a::Animal) = "Hello, $(a.name)!"
九、类型别名(Type Alias)
const Vec = Vector{Float64}
const Matrix = Array{Float64, 2}
v::Vec = [1.0, 2.0]
十、类型推断示例
julia> x = [1, 2, 3]
3-element Vector{Int64}:
1
2
3
julia> y = [1, 2.0, 3]
3-element Vector{Float64}:
1.0
2.0
3.0
julia> z = [1, "hi"]
2-element Vector{Any}:
1
"hi"
Julia 自动推断最具体共同类型
十一、类型可视化工具
using AbstractTrees
# 打印类型树
print_tree(Number)
输出:
Number
├─ Complex
└─ Real
├─ AbstractFloat
│ ├─ BigFloat
│ ├─ Float16
│ ├─ Float32
│ └─ Float64
├─ Integer
│ ├─ Bool
│ └─ Signed
│ ├─ BigInt
│ ├─ Int128
│ ├─ Int16
│ ├─ Int32
│ ├─ Int64
│ └─ Int8
└─ Rational
十二、数据类型速查表
| 类型 | 字面量 | 说明 |
|---|---|---|
Int64 | 42 | 默认整数 |
Float64 | 3.14 | 默认浮点 |
Bool | true | 布尔 |
Char | 'A' | 字符 |
String | "hi" | 字符串 |
Vector{T} | [1,2,3] | 一维数组 |
Tuple | (1,2,3) | 不可变序列 |
NamedTuple | (a=1, b=2) | 带名元组 |
Dict | Dict("a"=>1) | 键值对 |
Set | Set([1,2]) | 无序集合 |
Symbol | :x | 符号 |
Nothing | nothing | 无值 |
Missing | missing | 缺失值 |
小练习(立即上手)
- 定义一个
RGB命名元组类型别名 - 写函数判断变量是否为整数类型
- 创建
Union{Int, Float64}数组并求和 - 用
@code_warntype检查类型稳定性
答案示例
# 1. RGB 类型别名
const RGB = NamedTuple{(:r,:g,:b), Tuple{UInt8,UInt8,UInt8}}
color = RGB(255, 128, 0)
# 2. 是否整数
is_integer_type(x) = typeof(x) <: Integer
# 3. Union 数组求和
nums = Union{Int, Float64}[1, 2.5, 3, 4.0]
sum(nums) # 10.5
# 4. 类型检查
function bad(x)
if x > 0
return x
else
return "negative"
end
end
@code_warntype bad(5) # 显示 Union{Int64, String}
性能建议
| 建议 | 说明 |
|---|---|
避免 Any 和 Union | 降低性能 |
| 使用具体类型 | Vector{Float64} > Vector |
| 类型注解关键函数 | 提升 JIT 优化 |
| 预分配数组 | 避免动态增长 |
恭喜!你已掌握 Julia 数据类型系统!
下一站推荐:
需要我:
- 生成 完整类型树图?
- 写一个 类型检查器工具?
- 对比 Julia vs Python 类型系统?
随时告诉我!