Go by Example: Variables

In Go, variables are used to store values and can be assigned to different types of data. There are two ways to declare variables in Go, using the var keyword and using the short declaration operator :=.

Using the var Keyword

The var keyword is used to declare a variable and is followed by the name of the variable, the type, and the value. Here’s an example:

package main

import "fmt"

func main() {
    var name string = "John Doe"
    fmt.Println("Name:", name)
}

Using the Short Declaration Operator :=

The short declaration operator := can be used to declare a variable and assign a value to it in a single line. The type of the variable is inferred from the value. Here’s an example:

package main

import "fmt"

func main() {
    name := "John Doe"
    fmt.Println("Name:", name)
}

Multiple Variables

You can declare multiple variables on a single line, separated by commas. Here’s an example:

package main

import "fmt"

func main() {
    var name, age string = "John Doe", "25"
    fmt.Println("Name:", name)
    fmt.Println("Age:", age)
}

Variables can be declared without assigning a value. In this case, the zero value of the type is assigned to the variable. For example:

package main

import "fmt"

func main() {
    var name string
    fmt.Println("Name:", name)
}

In this tutorial, we’ve covered how to declare variables in Go using the var keyword and the short declaration operator :=. You can use variables to store values and manipulate them in your Go programs.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *