1 min read

How do you declare and initialize variables in Golang?

How do you declare and initialize variables in Golang?
Photo by Riccardo Annandale / Unsplash

Introduction

As with other programming language, Golang do have support of variables, as data to operate in memory. In this article, there will be presented several ways to declare and/or initialize variables, that is allowed by Golang syntax.

How variable are defined in Golang?

Here are the steps on how to declare and initialize variables in Golang:

Declare the variable.

The var keyword is used to declare a variable in Golang. The syntax for declaring a variable is as follows:

var variable_name variable_type

For example, the following code declares a variable named my_name of type string:

var my_name string

Initialize the variable.

The variable can be initialized with a value by using the = operator. For example, the following code initializes the variable my_name with the value "John Doe":

var my_name string = "John Doe"

Shorthand declaration.

Golang also supports a shorthand declaration syntax for declaring and initializing variables. The shorthand declaration syntax is as follows:

variable_name := value

For example, the following code declares and initializes the variable my_name with the value "John Doe" using the shorthand declaration syntax:

my_name := "John Doe"

Here are some of the rules for declaring and initializing variables in Golang:

  • The variable name must be a valid identifier.
  • The variable type must be a valid Golang type.
  • The value of the variable must be a valid value of the specified type.
  • The variable can be declared at the package level or the function level.
  • The variable can be declared with or without an initializer.