赋值运算符 #

一、基本赋值 #

1.1 赋值运算符 = #

julia
x = 10
name = "Julia"
arr = [1, 2, 3]

1.2 类型注解赋值 #

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

1.3 多重赋值 #

julia
a, b, c = 1, 2, 3
x, y = [10, 20]
first, second = (1, 2)

1.4 链式赋值 #

julia
a = b = c = 0
x = y = z = 100

二、复合赋值运算符 #

2.1 运算符列表 #

运算符 等价形式 示例
+= x = x + y x += 5
-= x = x - y x -= 3
*= x = x * y x *= 2
/= x = x / y x /= 2
÷= x = x ÷ y x ÷= 2
\= x = y \ x x \= 2
^= x = x ^ y x ^= 2
%= x = x % y x %= 10

2.2 算术复合赋值 #

julia
x = 10
x += 5
x -= 3
x *= 2
x /= 4
x ÷= 2
x ^= 2
x %= 10

2.3 位运算复合赋值 #

julia
x = 0b1010
x &= 0b1100
x |= 0b0011
x ⊻= 0b1111
x <<= 2
x >>= 1

三、数组赋值 #

3.1 索引赋值 #

julia
arr = [1, 2, 3, 4, 5]
arr[1] = 10
arr[end] = 50

3.2 切片赋值 #

julia
arr = [1, 2, 3, 4, 5]
arr[1:3] = [10, 20, 30]
arr[2:2:end] .= 0

3.3 广播赋值 #

julia
arr = [1, 2, 3, 4, 5]
arr .+= 1
arr .*= 2
arr .^= 2

四、字典赋值 #

4.1 键值赋值 #

julia
d = Dict{String, Int}()
d["a"] = 1
d["b"] = 2

4.2 修改值 #

julia
d = Dict("a" => 1, "b" => 2)
d["a"] += 10
d["b"] *= 2

五、结构体赋值 #

5.1 可变结构体 #

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

p = Point(1.0, 2.0)
p.x = 10.0
p.y += 5.0

5.2 不可变结构体 #

julia
struct ImmutablePoint
    x::Float64
    y::Float64
end

p = ImmutablePoint(1.0, 2.0)
p.x = 10.0

六、解构赋值 #

6.1 元组解构 #

julia
t = (1, 2, 3)
a, b, c = t

6.2 数组解构 #

julia
arr = [10, 20, 30]
x, y, z = arr

6.3 命名元组解构 #

julia
nt = (a=1, b=2, c=3)
(; a, b, c) = nt

6.4 忽略值 #

julia
t = (1, 2, 3, 4, 5)
a, _, c = t
first, _, _, _, last = t

七、实践练习 #

7.1 练习1:计数器 #

julia
mutable struct Counter
    value::Int
end

function increment!(c::Counter, delta::Int=1)
    c.value += delta
    return c.value
end

counter = Counter(0)
increment!(counter)
increment!(counter, 5)

7.2 练习2:累加器 #

julia
function accumulator()
    total = 0
    function add(value)
        total += value
        return total
    end
    return add
end

acc = accumulator()
acc(10)
acc(5)
acc(3)

7.3 练习3:交换变量 #

julia
function swap!(a, b)
    a, b = b, a
    return a, b
end

x, y = 1, 2
x, y = swap!(x, y)

八、总结 #

本章我们学习了:

  1. 基本赋值:=运算符
  2. 复合赋值:+=、-=、*=等
  3. 多重赋值:同时赋多个值
  4. 链式赋值:连续赋值
  5. 解构赋值:元组和数组解构

接下来让我们学习Julia的运算符优先级!

最后更新:2026-03-27