CodeToLive

Variables and Data Types in Go

In Go, variables are explicitly declared and used by the compiler to check type correctness. Go supports various data types, including integers, floats, strings, and booleans. Variables are essential for storing and manipulating data in programs.

Declaring Variables

Variables in Go can be declared using the var keyword or using the shorthand := syntax. The shorthand syntax is preferred for brevity and readability.


// Using var keyword
var age int = 25

// Using shorthand syntax
name := "Alice"
      

Common Data Types

Go provides several built-in data types to represent different kinds of data:

Type Inference

Go supports type inference, meaning the compiler can automatically determine the type of a variable based on the assigned value.


package main

import "fmt"

func main() {
    var age = 25 // Type inferred as int
    name := "Alice" // Type inferred as string
    isStudent := true // Type inferred as bool

    fmt.Println("Name:", name)
    fmt.Println("Age:", age)
    fmt.Println("Is Student:", isStudent)
}
      

Constants

Constants are fixed values that cannot be changed during program execution. They are declared using the const keyword.


package main

import "fmt"

const Pi = 3.14159

func main() {
    fmt.Println("Value of Pi:", Pi)
}
      

Variable Scope

The scope of a variable determines where it can be accessed in a program. Variables can have:


package main

import "fmt"

var globalVar = 10 // Global variable

func main() {
    localVar := 20 // Local variable
    fmt.Println("Global Variable:", globalVar)
    fmt.Println("Local Variable:", localVar)
}
      

Zero Values

In Go, variables declared without an explicit initial value are given their zero value. The zero value depends on the type:


package main

import "fmt"

func main() {
    var i int
    var f float64
    var b bool
    var s string

    fmt.Println("int zero value:", i)
    fmt.Println("float64 zero value:", f)
    fmt.Println("bool zero value:", b)
    fmt.Println("string zero value:", s)
}
      

Best Practices

Next: Control Structures