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

package main

var globalVar = "I'm global"  // accessible throughout the package

func main() {
    // can access globalVar here
}

2. Function Level

func main() {
    localVar := "I'm local"  // only accessible within main()
}

3. Block Level

func main() {
    if true {
        blockVar := "I'm in a block"  // only accessible within if block
    }
    // blockVar is not accessible here
}

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

var (
    i int         // 0
    f float64     // 0.0
    b bool        // false
    s string      // ""
    p *int        // nil
)

Constants

Constants are declared using the const keyword:

const (
    Pi = 3.14159
    MaxAge = 120
    Greeting = "Hello"
)

// iota for enumerated constants
const (
    Sunday = iota    // 0
    Monday          // 1
    Tuesday         // 2
    Wednesday       // 3
    Thursday        // 4
    Friday         // 5
    Saturday        // 6
)

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)

    for i := 0; i < 10; i++ { }
  2. Use Descriptive Names:

    • For package-level variables

    var (
        maxConnections = 100
        defaultTimeout = time.Second * 30
    )
  3. Group Related Variables:

    var (
        firstName, lastName string
        age int
    )
  4. Avoid Redundant Names:

    // Good
    var count int
    
    // Bad
    var countNumber int

Common Patterns

1. Error Checking

if err := doSomething(); err != nil {
    return err
}

2. Multiple Return Values

name, age, err := getPerson()
if err != nil {
    return err
}

3. Blank Identifier

// Ignore second return value
name, _ := getPerson()

Variable Type Conversion

var i int = 42
var f float64 = float64(i)
var s string = strconv.Itoa(i)  // Convert int to string

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?