Go Tutorials

Go Programs

Go Variables


Go Variables

In this tutorial, we will learn about variables in Go language. We will cover the basics of declaring and using variables, including naming conventions.


What are Variables

Variables in Go are used to store data values that can be manipulated during program execution. They have a type that determines the kind of data they can hold, such as integers, strings, or boolean values.


Naming Variables

When naming variables in Go, follow these conventions:

  • Start with a letter or an underscore (_).
  • Subsequent characters can include letters, digits, or underscores.
  • Avoid using reserved keywords as variable names.
  • Use meaningful and descriptive names to enhance code readability.

Syntax

The syntax to declare variables in Go is:

var variable_name data_type


Variable storing Integer Value

We can store an integer value in a variable.

For example,

  1. Declare an integer variable named num.
  2. Assign a value of 10 to the variable.
  3. Print the value of the variable.

Go Program

package main

import (
	"fmt"
)

func main() {
	// Declare and initialize an integer variable
	num := 10
	// Print the value of the variable
	fmt.Println("The value of num is:", num)
}

Output

The value of num is: 10


Variable storing String Value

We can store a string value in a variable.

For example,

  1. Declare a string variable named name.
  2. Assign the value 'John' to the variable.
  3. Print the value of the variable.

Go Program

package main

import (
	"fmt"
)

func main() {
	// Declare and initialize a string variable
	name := "John"
	// Print the value of the variable
	fmt.Println("The value of name is:", name)
}

Output

The value of name is: John


Variable storing Boolean Value

We can store a boolean value in a variable.

For example,

  1. Declare a boolean variable named isTrue.
  2. Assign the value true to the variable.
  3. Print the value of the variable.

Go Program

package main

import (
	"fmt"
)

func main() {
	// Declare and initialize a boolean variable
	isTrue := true
	// Print the value of the variable
	fmt.Println("The value of isTrue is:", isTrue)
}

Output

The value of isTrue is: true