Module: Go Basics

Variables

Go Programming: Variables

Variables are fundamental building blocks in any programming language, and Go is no exception. They allow you to store data that your program can manipulate. Here's a breakdown of variables in Go:

1. Declaration and Initialization

In Go, you declare a variable using the var keyword. There are several ways to do this:

a) Explicit Type Declaration:

var name string
var age int
var isStudent bool

This declares variables name, age, and isStudent with the types string, int, and bool respectively. Initially, these variables are assigned their zero value:

  • string: "" (empty string)
  • int: 0
  • bool: false
  • Pointers, slices, maps, functions, interfaces: nil

You can also initialize them during declaration:

var name string = "Alice"
var age int = 30
var isStudent bool = true

b) Type Inference (Short Variable Declaration):

Go can often infer the type of a variable based on the value assigned to it. This is done using the := operator (short variable declaration). This operator only works inside functions.

name := "Bob"  // Type is inferred as string
age := 25      // Type is inferred as int
isStudent := false // Type is inferred as bool

c) Multiple Variable Declaration:

You can declare multiple variables of the same type in a single line:

var x, y, z int
x = 10
y = 20
z = 30

// Or with initialization:
var a, b, c string = "apple", "banana", "cherry"

// Using short variable declaration:
p, q, r := 1, 2, 3

2. Variable Types

Go has several built-in data types:

  • Integer Types:
    • int: Platform-dependent size (usually 32 or 64 bits). Use this for general-purpose integers.
    • int8: 8-bit signed integer (-128 to 127)
    • int16: 16-bit signed integer (-32768 to 32767)
    • int32: 32-bit signed integer (-2147483648 to 2147483647)
    • int64: 64-bit signed integer (-9223372036854775808 to 9223372036854775807)
    • uint: Platform-dependent unsigned integer.
    • uint8: 8-bit unsigned integer (0 to 255) - often used for bytes.
    • uint16: 16-bit unsigned integer (0 to 65535)
    • uint32: 32-bit unsigned integer (0 to 4294967295)
    • uint64: 64-bit unsigned integer (0 to 18446744073709551615)
  • Floating-Point Types:
    • float32: 32-bit floating-point number.
    • float64: 64-bit floating-point number (default).
  • Boolean Type:
    • bool: true or false.
  • String Type:
    • string: Immutable sequence of bytes.
  • Complex Types:
    • complex64: Complex number with float32 real and imaginary parts.
    • complex128: Complex number with float64 real and imaginary parts.

3. Zero Values

As mentioned earlier, variables in Go are automatically initialized to their zero value if you don't explicitly assign a value. This is a crucial feature that helps prevent unexpected behavior.

Type Zero Value
int 0
float64 0.0
bool false
string ""
pointer nil
slice nil
map nil

4. Constants

Constants are values that cannot be changed after they are defined. They are declared using the const keyword.

const pi float64 = 3.14159
const greeting string = "Hello, world!"

// Multiple constants:
const (
    StatusOK     = 200
    NotFound     = 404
    InternalError = 500
)

Constants must be known at compile time, so they can only be assigned literal values or other constants.

5. Scope

The scope of a variable determines where in your code it can be accessed.

  • Global Scope: Variables declared outside of any function have global scope and can be accessed from anywhere in the package. (Use sparingly).
  • Function Scope: Variables declared inside a function are only accessible within that function.
  • Block Scope: Variables declared within a block of code (e.g., inside an if statement or for loop) are only accessible within that block.

6. Blank Identifier (_)

The blank identifier _ is used to discard values. It's often used when you want to ignore a return value from a function.

_, err := someFunction() // Ignore the first return value, check for error
if err != nil {
    // Handle the error
}

Example Program

package main

import "fmt"

func main() {
    var message string = "Hello, Go!"
    fmt.Println(message)

    age := 28
    fmt.Println("Age:", age)

    var x, y int = 5, 10
    fmt.Println("x + y =", x + y)

    const gravity float64 = 9.81
    fmt.Println("Gravity:", gravity)
}

This covers the basics of variables in Go. Understanding these concepts is essential for writing effective Go programs. Remember to choose appropriate data types for your variables to optimize performance and ensure data integrity.