Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Go Programming Tutorial: Variables

Introduction to Variables

Variables are fundamental to any programming language. They are used to store data that can be manipulated and accessed throughout a program. In Go, variables are explicitly declared and can hold different types of data, such as integers, strings, or floats.

Declaring Variables

In Go, variables can be declared using the var keyword. The syntax for declaring a variable is:

var variableName type

For example, to declare an integer variable named x:

var x int

Initializing Variables

Variables can also be initialized at the time of declaration:

var x int = 5

Go also supports type inference, which means you can omit the type if you initialize the variable:

var x = 5

The type of x will be inferred from the value assigned to it.

Short Variable Declaration

Go provides a shorthand for declaring and initializing variables using the := operator. This is often used within functions:

x := 5

Here, x is declared and initialized to 5, and its type is inferred from the value.

Multiple Variable Declaration

Multiple variables can be declared in a single line:

var a, b, c int

They can also be initialized together:

var a, b, c int = 1, 2, 3

Or using type inference:

var a, b, c = 1, 2, "three"

Variable Scope

Variables in Go have block scope. A variable declared inside a function or block is only accessible within that function or block. For example:

package main

import "fmt"

func main() {
    x := 10
    fmt.Println(x) // prints 10
}

func anotherFunction() {
    // fmt.Println(x) would cause an error because x is not accessible here
}

Constants

Constants are similar to variables but with a fixed value. They are declared using the const keyword:

const pi = 3.14

Constants cannot be declared using the := syntax.

Examples

Here is a complete example demonstrating variable declaration, initialization, and scope:

package main

import "fmt"

func main() {
    var a int = 10
    b := 20

    fmt.Println(a)
    fmt.Println(b)

    const pi = 3.14
    fmt.Println(pi)

    {
        c := 30
        fmt.Println(c)
    }

    // fmt.Println(c) would cause an error
}

Conclusion

Understanding variables is crucial for any Go programmer. They form the foundation of data manipulation in your programs. Practice declaring, initializing, and using variables to become proficient in Go programming.