Assign and swap values in Go
Change an existing value
Assignment with = stores a new value in an existing variable. It does not declare a new name. The assigned value must be compatible with the variable’s type. Here we first declare stock, then update it after a sale.
package main
import "fmt"
func main() { stock := 10 stock = stock - 2 fmt.Println(stock)}The expression on the right is evaluated using the old value 10, then the result 8 is assigned to stock. The variable is still an integer. Assigning "eight" would not be allowed.
Swap without a temporary variable
package main
import "fmt"
func main() { left, right := 3, 9 left, right = right, left fmt.Println(left, right)}The output is 9 3. For these simple variables Go evaluates the right-hand values before performing the assignments. With two separate statements left = right and right = left, both would become 9 because the original left value would be lost. In multiple assignment the number of values must match the targets; function calls returning several values are covered later.
Try it locally
Declare first=7 and second=2 using :=. Swap them with one assignment and print both. Expected: 2 7. Hint: put both original values on the right in reverse order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tokens and Declarations 05: Assign and swap values in Go
Check the lesson objective before moving on.
Which statement updates an existing x without declaring a new variable?
What follows a, b = b, a when a is 1 and b is 4?