类型注解 #

一、基本语法 #

1.1 ::操作符 #

::操作符用于类型注解:

julia
x::Int = 10
y::Float64 = 3.14
name::String = "Julia"

1.2 类型断言 #

::可以用于类型断言:

julia
x = 10
x::Int
x::Float64

1.3 类型转换 #

::可以用于类型转换:

julia
x = 10.5
x::Int

二、变量类型注解 #

2.1 全局变量 #

julia
global x::Int = 10

function modify_x()
    global x += 1
end

x
modify_x()
x

2.2 局部变量 #

julia
function process()
    x::Int = 10
    x += 1
    return x
end

process()

2.3 类型限制 #

julia
x::Int = 10
x = "hello"

三、函数参数注解 #

3.1 参数类型 #

julia
function add(a::Int, b::Int)
    a + b
end

add(1, 2)
add(1.0, 2.0)

3.2 多种类型 #

julia
function process(x::Union{Int, Float64})
    x * 2
end

process(10)
process(10.5)
process("hello")

3.3 参数化类型 #

julia
function first(arr::Vector{T}) where {T}
    arr[1]
end

first([1, 2, 3])
first(["a", "b", "c"])

四、返回类型注解 #

4.1 基本语法 #

julia
function add(a::Int, b::Int)::Int
    a + b
end

4.2 复杂类型 #

julia
function create_point(x, y)::Tuple{Float64, Float64}
    (Float64(x), Float64(y))
end

create_point(1, 2)

4.3 Union返回类型 #

julia
function safe_divide(a, b)::Union{Float64, Nothing}
    b == 0 ? nothing : a / b
end

safe_divide(10, 2)
safe_divide(10, 0)

五、字段类型注解 #

5.1 结构体字段 #

julia
struct Point
    x::Float64
    y::Float64
end

p = Point(1.0, 2.0)
p.x

5.2 参数化字段 #

julia
struct Container{T}
    value::T
end

Container(10)
Container("hello")

六、类型注解的作用 #

6.1 文档作用 #

julia
function calculate_area(width::Float64, height::Float64)::Float64
    width * height
end

6.2 类型检查 #

julia
function process(x::Int)
    x * 2
end

process(10)
process(10.0)

6.3 性能优化 #

julia
function sum_array(arr::Vector{Int})
    total = 0
    for x in arr
        total += x
    end
    total
end

七、实践练习 #

7.1 练习1:类型安全函数 #

julia
function divide(a::Real, b::Real)::Float64
    b == 0 && error("Division by zero")
    a / b
end

divide(10, 2)
divide(10.0, 2.0)
divide(10, 0)

7.2 练习2:类型转换函数 #

julia
function to_string(x)::String
    string(x)
end

to_string(10)
to_string(3.14)
to_string([1, 2, 3])

7.3 练习3:类型检查工具 #

julia
function type_check(x, expected_type::Type)
    if x isa expected_type
        println("✓ $x is $expected_type")
        return true
    else
        println("✗ $x is $(typeof(x)), expected $expected_type")
        return false
    end
end

type_check(1, Int)
type_check(1.0, Int)
type_check("hello", String)

八、总结 #

本章我们学习了:

  1. ::操作符:类型注解和断言
  2. 变量注解:全局和局部变量
  3. 参数注解:函数参数类型
  4. 返回类型注解:函数返回类型
  5. 字段注解:结构体字段类型

接下来让我们学习Julia的方法与多重派发!

最后更新:2026-03-27