Variables

Variable Declaration

There are several ways to declare variables in Go:

1. Using var keyword

var name string        // declares variable with zero value ("")
var age int = 25      // declares and initializes
var isActive = true   // type inferred from value

2. Short Declaration (:=)

name := "John"        // type string inferred
age := 25            // type int inferred

3. Multiple Declarations

var (
    name    string
    age     int
    isValid bool
)

// Multiple short declarations
name, age := "John", 25

Variable Scope

1. Package Level

2. Function Level

3. Block Level

Zero Values

Go automatically assigns zero values to declared variables:

  • Numeric types: 0

  • Boolean type: false

  • String type: ""

  • Pointer type: nil

  • Reference types (slice, map, channel, interface): nil

Constants

Constants are declared using the const keyword:

Variable Naming Conventions

  1. CamelCase is the conventional style:

    • userName (private)

    • UserName (public - exported)

  2. Common Abbreviations:

    • i for index

    • err for error

    • ctx for context

Best Practices

  1. Use Short Variable Names:

    • For short-lived variables (loops, small functions)

  2. Use Descriptive Names:

    • For package-level variables

  3. Group Related Variables:

  4. Avoid Redundant Names:

Common Patterns

1. Error Checking

2. Multiple Return Values

3. Blank Identifier

Variable Type Conversion

Tips and Tricks

  1. Use := when possible:

    • Shorter and cleaner than var

    • But remember it can't be used at package level

  2. Declare variables close to use:

    • Keeps code readable

    • Makes scope clear

  3. Group related declarations:

    • Improves readability

    • Shows relationships between variables

  4. Use meaningful names:

    • Variables should be descriptive

    • Length of name should match scope size

Additional Resources

Last updated

Was this helpful?