Skip to content

Julia 数据类型

Julia 是动态类型语言,但拥有强大的类型系统。理解 Julia 的类型系统有助于编写高效的代码。

类型层次结构

Julia 的类型形成一个层次树,Any 是所有类型的根类型:

Any
├── Number
│   ├── Real
│   │   ├── Integer
│   │   │   ├── Bool
│   │   │   ├── Int8, Int16, Int32, Int64, Int128
│   │   │   └── UInt8, UInt16, UInt32, UInt64, UInt128
│   │   └── AbstractFloat
│   │       ├── Float16, Float32, Float64
│   │       └── BigFloat
│   └── Complex
├── AbstractString
│   └── String
├── AbstractArray
│   └── Array
└── ...

数值类型

整数类型

julia
# 有符号整数
a = Int8(127)      # -128 到 127
b = Int16(1000)    # -32768 到 32767
c = Int32(100000)  # 约 ±21亿
d = Int64(10)      # 默认类型(64位系统)
e = Int128(10)     # 非常大的整数

# 无符号整数
f = UInt8(255)     # 0 到 255
g = UInt16(65535)  # 0 到 65535
h = UInt64(10)

# 任意精度整数
big_num = big(10)^100  # BigInt

类型范围

julia
println(typemin(Int8))   # -128
println(typemax(Int8))   # 127
println(typemin(Int64))  # -9223372036854775808
println(typemax(Int64))  # 9223372036854775807

浮点类型

julia
# 浮点数
a = Float16(1.5)   # 半精度(2字节)
b = Float32(1.5)   # 单精度(4字节)
c = Float64(1.5)   # 双精度(8字节,默认)
d = BigFloat(1.5)  # 任意精度

# 特殊值
println(Inf)       # 正无穷
println(-Inf)      # 负无穷
println(NaN)       # 非数字

# 检查特殊值
println(isinf(Inf))   # true
println(isnan(NaN))   # true
println(isfinite(1.0)) # true

布尔类型

julia
t = true
f = false

println(typeof(t))  # Bool

# 布尔值也是整数
println(true + true)   # 2
println(false + true)  # 1

字符与字符串

字符(Char)

julia
# 单个字符用单引号
c = 'A'
println(typeof(c))  # Char

# Unicode 字符
alpha = 'α'
chinese = '中'

# 字符码
println(Int('A'))   # 65
println(Char(65))   # 'A'

字符串(String)

julia
# 字符串用双引号
s = "Hello, Julia!"
println(typeof(s))  # String

# 多行字符串
multiline = """
第一行
第二行
第三行
"""

# 原始字符串(不转义)
raw = raw"C:\Users\name"  # 不需要转义反斜杠

复合类型

结构体(struct)

julia
# 不可变结构体
struct Point
    x::Float64
    y::Float64
end

p = Point(3.0, 4.0)
println(p.x)  # 3.0
println(p.y)  # 4.0

# 可变结构体
mutable struct MutablePoint
    x::Float64
    y::Float64
end

mp = MutablePoint(1.0, 2.0)
mp.x = 10.0  # 可以修改
println(mp.x)  # 10.0

带默认值的结构体

julia
# 使用内部构造函数
struct Rectangle
    width::Float64
    height::Float64
    
    function Rectangle(w, h=w)  # h 默认等于 w(正方形)
        new(w, h)
    end
end

r1 = Rectangle(5.0, 3.0)
r2 = Rectangle(5.0)  # 正方形

参数化类型

julia
# 泛型结构体
struct Container{T}
    value::T
end

c1 = Container(42)       # Container{Int64}
c2 = Container("hello")  # Container{String}
c3 = Container(3.14)     # Container{Float64}

println(typeof(c1))  # Container{Int64}

抽象类型

julia
# 定义抽象类型
abstract type Animal end
abstract type Mammal <: Animal end

# 具体类型继承抽象类型
struct Dog <: Mammal
    name::String
end

struct Cat <: Mammal
    name::String
end

# 检查类型关系
println(Dog <: Mammal)   # true
println(Dog <: Animal)   # true
println(Int <: Number)   # true

类型检查与转换

类型检查

julia
x = 42

# 获取类型
println(typeof(x))  # Int64

# 类型判断
println(isa(x, Int))      # true
println(isa(x, Number))   # true
println(isa(x, String))   # false

# 使用 :: 断言类型
function process(x::Int)
    return x * 2
end

类型转换

julia
# 使用构造函数转换
a = Int(3.0)      # 3(Float64 -> Int)
b = Float64(42)   # 42.0(Int -> Float64)

# convert 函数
c = convert(Float64, 42)  # 42.0

# parse 解析字符串
d = parse(Int, "42")      # 42
e = parse(Float64, "3.14") # 3.14

# string 转字符串
s = string(42)            # "42"
s = string(3.14)          # "3.14"

Union 类型

Union 类型表示可以是多种类型之一:

julia
# 定义 Union 类型
IntOrString = Union{Int, String}

function process(x::IntOrString)
    if x isa Int
        println("整数: $x")
    else
        println("字符串: $x")
    end
end

process(42)       # 整数: 42
process("hello")  # 字符串: hello

类型别名

julia
# 创建类型别名
const IntVector = Vector{Int}
const StringDict = Dict{String, Any}

# 使用别名
v::IntVector = [1, 2, 3]
d::StringDict = Dict("a" => 1, "b" => "hello")

类型参数

参数化函数

julia
# 指定参数类型
function double(x::T) where T <: Number
    return x * 2
end

println(double(5))     # 10
println(double(3.14))  # 6.28

多个类型参数

julia
function combine(x::T, y::S) where {T, S}
    return (x, y, T, S)
end

result = combine(1, "hello")
println(result)  # (1, "hello", Int64, String)

类型稳定性

类型稳定的函数性能更好:

julia
# 类型不稳定(不推荐)
function bad_example(x)
    if x > 0
        return x      # Int
    else
        return 0.0    # Float64
    end
end

# 类型稳定(推荐)
function good_example(x)
    if x > 0
        return float(x)  # 总是返回 Float64
    else
        return 0.0
    end
end

常用类型函数

julia
x = 42

# 类型信息
println(typeof(x))       # Int64
println(supertype(Int))  # Signed
println(subtypes(Number)) # 所有 Number 的子类型

# 类型判断
println(isa(x, Int))     # true
println(x isa Number)    # true(中缀形式)

# 类型关系
println(Int <: Number)   # true
println(Int <: String)   # false

# 类型属性
println(isconcretetype(Int))    # true
println(isabstracttype(Number)) # true

类型注解最佳实践

julia
# 1. 函数参数使用抽象类型
function sum_numbers(arr::AbstractVector{<:Number})
    return sum(arr)
end

# 2. 返回类型注解(可选但有助于文档)
function divide(a::Int, b::Int)::Float64
    return a / b
end

# 3. 结构体字段使用具体类型
struct Person
    name::String
    age::Int
end

# 4. 避免全局变量的类型不确定性
const GLOBAL_CONSTANT::Int = 100

下一步

学习完数据类型后,请继续学习:

本站内容仅供学习和研究使用。