What does ":=" do?

Learn what does ":=" do? with practical examples, diagrams, and best practices. Covers operators, colon-equals development techniques with visual explanations.

Understanding the := Operator: Assignment vs. Comparison

Hero image for What does ":=" do?

Explore the diverse functionalities of the := operator across various programming languages and contexts, distinguishing it from the standard assignment operator.

The := operator, often referred to as the 'colon-equals' operator, holds distinct meanings and uses depending on the programming language or context in which it appears. While it might visually resemble a standard assignment operator (=), its functionality is frequently more specialized, ranging from variable declaration and assignment in one step to specific comparison or pattern matching operations. This article delves into its common applications, helping you understand when and where to expect this unique syntax.

Common Uses of :=

The := operator is not universally present in all programming languages. Where it does exist, its primary roles typically fall into a few categories:

  1. Declaration and Assignment (Walrus Operator): In languages like Python (since 3.8) and Go, := is used for a combined declaration and assignment. This allows for assigning values to variables as part of an expression, often simplifying code.
  2. Assignment in Pascal-like Languages: In languages such as Pascal, Ada, and Modula-2, := is the standard assignment operator, equivalent to = in C-like languages.
  3. Pattern Matching/Assignment in Functional Languages: Some functional programming languages or contexts use := for pattern matching or binding values within specific constructs.
  4. SQL and Database Contexts: In SQL, particularly within procedural extensions like PL/SQL (Oracle) or PostgreSQL's PL/pgSQL, := is the assignment operator for variables.
flowchart TD
    A[Start]
    B{"Is it Python (>=3.8) or Go?"}
    C{"Is it Pascal, Ada, or PL/SQL?"}
    D[Declaration & Assignment (Walrus/Short Decl.)]
    E[Standard Assignment Operator]
    F[Other Contexts (e.g., Pattern Matching)]
    G[End]

    A --> B
    B -- Yes --> D
    B -- No --> C
    C -- Yes --> E
    C -- No --> F
    D --> G
    E --> G
    F --> G

Decision flow for interpreting the := operator based on context.

The Walrus Operator in Python

Python 3.8 introduced the assignment expression operator :=, famously dubbed the 'walrus operator' due to its visual resemblance to a walrus's eyes and tusks. Its primary purpose is to assign values to variables as part of a larger expression. This can lead to more concise code, especially in if conditions, while loops, and list comprehensions, where you might otherwise have to compute a value and then assign it in a separate line.

# Traditional approach
# data = [1, 2, 3, 4, 5]
# n = len(data)
# if n > 3:
#     print(f"List is long ({n} elements)")

# Using the walrus operator
data = [1, 2, 3, 4, 5]
if (n := len(data)) > 3:
    print(f"List is long ({n} elements)")

# In a while loop
# user_input = input("Enter something (or 'quit'): ")
# while user_input != 'quit':
#     print(f"You entered: {user_input}")
#     user_input = input("Enter something (or 'quit'): ")

# Using the walrus operator
while (user_input := input("Enter something (or 'quit'): ")) != 'quit':
    print(f"You entered: {user_input}")

Examples of Python's walrus operator (:=) for assignment expressions.

Short Variable Declaration in Go

In Go, := is used for short variable declarations. This operator declares and initializes a variable in a single step, and Go automatically infers the variable's type from the assigned value. It can only be used inside functions. For package-level variables or when you need to explicitly declare a type without immediate initialization, the var keyword is used.

package main

import "fmt"

func main() {
    // Short variable declaration: declares 'message' and assigns a string
    message := "Hello, Go!"
    fmt.Println(message)

    // Declaring and assigning multiple variables
    x, y := 10, 20
    fmt.Printf("x: %d, y: %d\n", x, y)

    // This would be a compile-time error if 'result' was already declared
    // result := 100 // Error: no new variables on left side of :=

    // Reassignment (if at least one new variable is declared)
    x, z := 30, "new string"
    fmt.Printf("x: %d, z: %s\n", x, z)
}

Go's short variable declaration using :=.

Assignment in Pascal-like Languages and SQL PL/pgSQL

For languages like Pascal, Ada, and Modula-2, := is the fundamental assignment operator. It explicitly distinguishes assignment from the equality comparison operator, which is typically =.

Similarly, in SQL procedural extensions such as PostgreSQL's PL/pgSQL or Oracle's PL/SQL, := is used to assign values to variables within stored procedures, functions, and triggers. This helps differentiate variable assignment from SQL's equality comparison in WHERE clauses.

Pascal

program Example; var count: Integer; message: String; begin count := 10; { Assigns 10 to count } message := 'Hello, Pascal!'; { Assigns string to message } writeln(message, ' Count: ', count); end.

PL/pgSQL (PostgreSQL)

DO $$ DECLARE my_variable INTEGER; greeting TEXT; BEGIN my_variable := 42; -- Assigns 42 to my_variable greeting := 'Hello from PL/pgSQL!'; -- Assigns string to greeting RAISE NOTICE 'Variable: %, Greeting: %', my_variable, greeting; END $$;