Assignment and compound assignment
= stores a new value in a place: a var, a field, an array element, or a map entry. The compound operators +=, -=, *=, /=, and %= combine the place's value with the right side and store the result.
Details
- An assignment is an expression of type
void. It cannot be chained or used as a condition. - A target is a
var, a field such asp.x, an element such asxs[i]orm[k], or an array destructuring such as[a, b]. Assigning aletname, a parameter, or a name aforbinds is a compile error. - The value must fit the target's declared type.
x += yfollows the rules ofx + y: both operands have one type, and integer overflow panics. On a map entry the read isV | null, so a compound operator is a compile error there. - The target's sub-expressions, such as the index in
xs[i] = v, evaluate before the right side. An array destructuring assignment then stores left to right. - A destructuring assignment allows only
=. There is no record destructuring assignment, and no++or--.
Basic examples
var count = 0
count = 5
count += 2
count // 7Each compound operator applies its arithmetic operator:
var n = 20
n -= 2
n *= 3
n /= 4
n %= 5
n // 3+= on a string appends:
var greeting = "Hello"
greeting += ", Ant"
greeting // "Hello, Ant"Scope
Fields and elements
A field or an element is a place too. A let fixes only the name, so the value's fields and elements can still be assigned:
type Point = { x: int, y: int }
let p = Point{ x: 1, y: 2 }
p.x += 10
p.y = 0
p // Point{ x: 11, y: 0 }
let xs = [1, 2, 3]
xs[0] = 9
xs[2] *= 10
xs // [9, 2, 30]A path of fields and indexes ends in one place:
type Point = { x: int, y: int }
let path = [Point{ x: 0, y: 0 }, Point{ x: 3, y: 4 }]
path[1].x *= 2
path // [Point{ x: 0, y: 0 }, Point{ x: 6, y: 4 }]Map entries
m[k] = v inserts a new entry or replaces the value of an existing one:
let ages = Map{ "Ann": 31 }
ages["Ann"] = 32
ages["Bob"] = 27
ages // Map{ "Ann": 32, "Bob": 27 }A compound operator reads the entry first, and a map read is V | null, so += on a map entry is a compile error. Add a default with ??:
let ages = Map{ "Ann": 31 }
ages["Ann"] += 1 // error: += on a map element reads it first, and the read is int | nullDestructuring
An array destructuring assigns several places at once. The right side is built before any position is stored, so [a, b] = [b, a] swaps:
var a = 1
var b = 2
[a, b] = [b, a]
a // 2
b // 1The positions can be any places, _ to skip a value, or ... for the rest:
type Point = { x: int, y: int }
let p = Point{ x: 0, y: 0 }
let xs = [0, 0]
var rest: Array[int] = []
[p.x, _, xs[1], ...rest] = [1, 2, 3, 4, 5]
p // Point{ x: 1, y: 0 }
xs // [0, 3]
rest // [4, 5]A destructuring nests when the elements are arrays:
var top = 0
var low = 0
[[top], [_, low]] = [[1, 2], [3, 4]]
top // 1
low // 4Discarding a value
_ = expr evaluates expr and discards its value:
func save(): int {
println("saved")
1
}
_ = save()savedClosures
A closure can assign a var it captures, and the change is seen outside:
var clicks = 0
let click = func() { clicks += 1 }
click()
click()
clicks // 2Evaluation order
The target's index runs before the right side:
func slot(): int {
println("index")
0
}
func value(): int {
println("value")
9
}
let xs = [1]
xs[slot()] = value()
println(xs)index
value
[9]Applications
Advance a pair in one step, as in a Fibonacci loop:
var a = 0
var b = 1
for _ in Iter.range(0, 10) {
[a, b] = [b, a + b]
}
println(a)55Count words in a map. Reading counts[word] gives null for a missing key, so add a default with ??:
let counts: Map[string, int] = Map{}
for word in "the ant and the bee".split(" ") {
counts[word] = (counts[word] ?? 0) + 1
}
println(counts)Map{ "the": 2, "ant": 1, "and": 1, "bee": 1 }Total a cart:
type Item = { price: int, qty: int }
let cart = [Item{ price: 3, qty: 2 }, Item{ price: 5, qty: 1 }]
var total = 0
for item in cart {
total += item.price * item.qty
}
println(total)11Properties and relations
A compound assignment is the same as assigning the result of its operator:
var x = 7
var y = 7
x *= 6
y = y * 6
assert(x == y)A destructuring assignment is the same as building the right side, then assigning each position in turn:
var a = 1
var b = 2
[a, b] = [b, a]
var c = 1
var d = 2
let tmp = [d, c]
c = tmp[0]
d = tmp[1]
assert([a, b] == [c, d])Possible issues
Assigning a let
A let name cannot be assigned, with = or a compound operator. Declare it with var:
let total = 0
total += 5 // error: cannot assign to total, a let; declare it with var to reassign itParameters are let bindings too. Copy one into a var to change it:
func countdown(n: int): int {
n -= 1 // error: cannot assign to n, a parameter; declare a var to hold a value that changes
n
}func countdown(n: int): int {
var left = n
left -= 1
left
}
countdown(3) // 2Assignment is not a value
An assignment has type void, so if cannot test it. Compare with ==:
var count = 0
if count = 5 { println("five") } // error: cannot use void where bool is expectedAssignments cannot be chained. Write one per target:
var a = 0
var b = 0
a = b = 3 // error: assignment cannot be chainedAssigning through a union
A field cannot be assigned through a union type, such as a nullable record. Narrow first:
type User = { name: string }
func rename(u: User | null) {
u.name = "Ann" // error: cannot assign a field through the union User | null; narrow first
}type User = { name: string }
func rename(u: User | null) {
if u == null {
return
}
u.name = "Ann"
}
let u = User{ name: "Bob" }
rename(u)
u.name // "Ann"No ++ or --
Write += 1 and -= 1 instead:
var i = 0
i++ // error: there is no ++: write += 1Mixed types
Both sides of a compound operator have one type. An int does not mix with a float64:
var total = 0.0
total += 1 // error: + needs both operands of one type, got float64 and intvar total = 0.0
total += 1.0
total // 1.0The value of = must fit the target's declared type. Declare a wider type up front:
var status = "idle"
status = null // error: cannot use null where string is expectedCompound destructuring
A destructuring assignment takes only =:
var a = 1
var b = 2
[a, b] += [10, 20] // error: a destructuring assignment allows only '='Out of range
Assigning past the end of an array panics; it does not grow the array. Use push to append:
let xs = [1, 2, 3]
xs[3] = 4 // panic: index 3 out of range for an array of length 3A destructuring with more positions than the array has elements panics:
var a = 0
var b = 0
[a, b] = [1] // panic: a destructuring needs 2 elements, got 1Overflow
A compound operator on integers panics on overflow, as the operator does:
var n = 9223372036854775807
n += 1 // panic: integer overflowSee also
var · let · Arithmetic operators · Indexing · ?? operator · void · Variables tour
