Go Basics

Go Variables

Description

Variables are containers for storing data values. In Go, `var` declares a list of variables; as in function argument lists, the type is last. Go also supports a short assignment syntax `:=` inside functions.

Pros & Cons

✅ Pros

  • Type Safety: Compiler checks types.
  • Flexibility: Short declaration makes code terse.

❌ Cons

  • Variable Shadowing: Be careful with `:=` in nested blocks.

When to Use

Storing state and data.

Example

Declaring variables in different ways.

package main
import "fmt"

func main() {
    var a int = 10         // Standard declaration
    var b = "Hello"        // Type inference
    c := 3.14              // Short declaration (func only)
    
    fmt.Println(a, b, c)
}

Best Practices

Prefer short declaration `:=` inside functions for brevity. Use `var` for package-level variables.

← Go CommentsGo Constants →