Go Declare Variables

Learning different ways to declare variables in Go

📝 How to Declare Variables?

Go offers multiple ways to declare variables. You can specify types explicitly, let Go infer types, or use short declarations for convenience and cleaner code.


// Different ways to declare variables
var name string = "Alice"
var age = 25
score := 95.5
fmt.Println(name, age, score)
                                    

Output:

Alice 25 95.5

Declaration Methods

🎯

Explicit Type

Declare with specific data type

var count int = 10
🤖

Type Inference

Let Go determine the type

var price = 19.99

Short Declaration

Quick syntax with := operator

name := "John"
🔄

Zero Value

Declare without initial value

var status bool

🔹 Method 1: var with Type and Value

The most explicit way to declare variables:

var firstName string = "John"
var lastName string = "Doe"
var age int = 30
var salary float64 = 50000.50
var isEmployed bool = true

fmt.Println("Name:", firstName, lastName)
fmt.Println("Age:", age)
fmt.Println("Salary:", salary)
fmt.Println("Employed:", isEmployed)

Output:

Name: John Doe

Age: 30

Salary: 50000.5

Employed: true

🔹 Method 2: var with Type Only

Declare variables with zero values:

var username string
var userAge int
var userHeight float64
var isActive bool

// Assign values later
username = "alice123"
userAge = 28
userHeight = 5.6
isActive = true

fmt.Printf("User: %s, Age: %d, Height: %.1f, Active: %t\n", 
           username, userAge, userHeight, isActive)

Output:

User: alice123, Age: 28, Height: 5.6, Active: true

🔹 Method 3: var with Type Inference

Let Go automatically determine the type:

var city = "New York"        // string
var population = 8400000     // int
var area = 302.6            // float64
var isCapital = false       // bool

fmt.Printf("City: %s\n", city)
fmt.Printf("Population: %d\n", population)
fmt.Printf("Area: %.1f sq miles\n", area)
fmt.Printf("Capital: %t\n", isCapital)

Output:

City: New York

Population: 8400000

Area: 302.6 sq miles

Capital: false

🔹 Method 4: Short Declaration (:=)

The most concise way (only inside functions):

func main() {
    // Short declarations
    product := "Laptop"
    price := 999.99
    inStock := true
    quantity := 15
    
    fmt.Printf("Product: %s\n", product)
    fmt.Printf("Price: $%.2f\n", price)
    fmt.Printf("In Stock: %t\n", inStock)
    fmt.Printf("Quantity: %d\n", quantity)
}

Output:

Product: Laptop

Price: $999.99

In Stock: true

Quantity: 15

🧠 Test Your Knowledge

Which operator is used for short variable declaration in Go?