Golang Variable: Different Ways to Create Variables in Golang

Robin
Updated on June 24, 2023

Variables play a fundamental role in programming languages, allowing us to store and manipulate data. Go (Golang) is a statically typed language. So, you will get type safety.

In Go, a variable is a named storage location that holds a value of a specific data type. It serves as a container for storing and manipulating data during program execution.

Variables in Go have a fixed type that you can specify explicitly while creating a variable otherwise the compiler will infer its type. There are many built-in variable types in Golang. You can also create your custom type if you need.

There are different ways to declare variables in Golang. Understanding the various techniques for creating variables is crucial for writing efficient and readable code.

In this blog post, we'll delve into the var keyword, shorthand notation, explicit typing, type inference, and other essential concepts related to the variable declaration.

Declare Variables in Golang Using var Keyword

The most common way to create variables in Go is by using the var keyword. you can declare variables with this keyword, providing explicit type information along with the initial value.

The syntax is as follows:

          var variableName type = value
        

Let's break down each part of this syntax:

  • var: This keyword is used to indicate the declaration of a variable.
  • variableName: It is the identifier or name given to the variable, which you can choose to represent its purpose or meaning in your code.
  • type: Specifies the data type of the variable, such as int, string, float64, or any other valid Go type.
  • value: Represents the initial value assigned to the variable. It must be compatible with the declared data type.

Also Read: Understanding All Data Types in Golang: A Complete Guide


Variable Declaration with Initialization

When you declare a variable with initialization, it means you are providing the initial value to that variable while creating.

By specifying the initial value during declaration, you can avoid a separate assignment statement, making your code more concise and readable.

          var age int = 25
var name string = "John"
        

We declare two variables called age of type int (integer) with the value 25 and name of type string with the value "John". By specifying the initial value during declaration, you don't have to assign a value separately.

It's important to note that the data type and value assigned must be compatible. Otherwise, a compilation error will occur. For example, you cannot assign a string value to an integer variable or vice versa.

          age = 27
name = "Max"
        

You can also reassign or change the initial value of a variable anytime you want by using its name.


Variable Declaration without Initialization

Sometimes you may want to declare a variable without immediately assigning it a value. It's like reserving a space in the memory for a specific type of data, but you don't have the actual value yet. You can achieve this using the var keyword.

Imagine you're building a program that needs to keep track of the number of users currently logged in.

You want to declare a variable to store this information, but you don't know the exact count at the moment. This is where the variable without initialization comes in handy.

You can declare the variable with the var keyword, provide a name for it, and specify its data type. For instance, you might declare a variable called loggedInUsers of type int like this:

          var loggedInUsers int
        

By using this syntax, you've created a variable called loggedInUsers that is of type int but doesn't have a value assigned yet. It acts as a placeholder, ready to store the number.

When you don't assign an initial value to a variable, Golang sets a default value to it based on the type. Here the loggedInUsers variable is of type int so Go will set 0 as its default value.

Later in your program, once you have the count of logged-in users, you can assign the value to the variable using an assignment statement.

          loggedInUsers = 10
        

Now, the loggedInUsers variable holds the value 10, representing the current count of users logged into your system.


Built-in Data Types in Golang

There are several built-in data types that provide a way to store and work with different kinds of data in Golang.

These data types are already available for you to use without requiring any additional setup. Each type has its own characteristics and usage scenarios.

  • Integers: Integers are used to store whole numbers without fractional parts. Go provides various integer types, such as int (platform-dependent size), int8, int16, int32, and int64, representing different ranges of numerical values.
  • Floating-Point Numbers: Floating-point types, including float32 and float64, are used to represent numbers with fractional parts. The default type for floating-point numbers is float64 in Go.
  • Strings: Strings are used to store sequences of characters, such as names, messages, or any textual data. In Go, strings are represented using double quotes ("") or backticks (``).
  • Booleans: Booleans have two possible values, either true or false. They are used to represent logical conditions and control flow in programs. The bool type is used for boolean variables.
  • Arrays: Arrays are fixed-size collections of elements of the same type. They allow you to store multiple values of the same data type in a contiguous block of memory.
  • Slices: Slices are dynamic and flexible representations of arrays. They provide a more convenient way to work with collections of elements. Slices can grow or shrink dynamically as needed.
  • Maps: Maps are used to store key-value pairs, where each key is unique. They provide an efficient way to access and retrieve values based on their associated keys.

These are just a few examples of the built-in variable types in Go. Each type has specific properties and methods associated with it. You can use them to perform various operations and manipulations on the data.


Shorthand Variable Declaration in Golang

You have seen how to create variables using the var keyword. But you can also create variables in Golang without the var keyword. This is called "Shorthand Notation".

Shorthand variable declaration provides a more concise and convenient way to declare and initialize variables. It allows you to declare a variable and assign it a value in a single line, without explicitly mentioning the var keyword.

The syntax is as follows:

          variableName := value
        

To declare variables with short notation, we use the := sign. When you create variables using this sign, you always have to provide the initial value.

In this case, you don't need to specify the type of your variable. The compiler will infer the type based on the initial value.

          age := 25
name := "John"
        

Here, I am creating the age variable with the value 25 and the name variable with the value "John" using the =: sign.

The initial value of age variable is 25 (integer), therefore Golang will set its type int automatically. In the same way, the type of the name variable will be string because of its value.

However, it's important to note that you can use shorthand variable declaration within functions. It is not possible to declare a variable with := sign in the global scope.


Differences Between var and := Sign

I have explained 2 techniques for creating variables in Golang. To understand when you should use which, it is important to know their differences.

These are some of their main differences:

  • Syntax: We use different syntax for these 2 techniques. One uses the var keyword and another uses the := sign.
  • Explicit vs. Inferred Type: You can explicitly specify the variable types with var keyword but := sign infers the variable type based on the assigned value.
  • Scope: You can declare variables inside and outside of functions with var keyword but := sign can only be used within functions or smaller scopes.
  • Initialization: The var keyword allows you to declare variables without initial values but you must provide initial values while creating variables using the := keyword.

Ultimately, the decision between var and := comes down to your personal preference. Most of the time developers like to create variables using := because it is concise and easy to write.

But if you need to declare variables outside a function or global scope, you have to use the var keyword.


Type Inference in Golang Variable

Type inference in Go refers to the ability of the compiler to automatically determine the type of a variable based on its assigned value. It allows you to declare variables without explicitly specifying the data type, relying on the compiler to infer it for you.

By default, variables with the := sign use type inference. But if you use the var keyword, you can specify the data type explicitly or you can rely on the compiler to infer the type based on the initial value.

          var age = 25
var name = "John"
        

Here I have created 2 variables called age and name using var keyword without giving any type. Therefore, the compiler will use type inference to decide their type.


Declare Multiple Variables in Golang

When we work on an application, we create multiple variables. You can declare multiple variables one by one or it is also possible to create them in one line.


Multiple Variables Using var Keyword

When we create multiple variables with the var keyword, we don't specify the types. Because using type inference, we can create variables with different data types.

          var name, age, isStudent = "John", 25, true
        

Here I have 3 variables name, age, and isStudent created in a single line. The name is a string, age is a int and isStudent is a bool type. As I am using type inference, it is possible to create variables with different types.

Specifying the data type:

          var firstName, lastName string = "John", "Doe"
        

When you explicitly want to add the type, you have to specify it at the end of the variable names. It is important to note that you can't create variables with different types.

That's why I am declaring firstName and lastName variables together, and both are string types.

Without specifying initial values:

          var firstName, lastName string
        

You can also declare multiple variables using var keyword without assigning their initial values and giving the value to them individually later.


Multiple Variables Using := Sign

The := sign allows you to declare and initialize multiple variables in a single line without explicitly stating the type.

          name, age, isStudent := "John", 25, true
        

I have declared three variables: "name", "age", and "isStudent". The type of each variable is inferred based on the assigned values: "name" is inferred as a string, "age" as an int, and "isStudent" as a bool.


Multiple Variables in a Block

You can declare multiple variables by grouping them in a block. You also need to use the var keyword.

With Initialization:

          var (
	name      string = "John"
	age       int    = 25
	isStudent bool   = true
)
        

Without Initialization:

          var (
	name      string = "John"
	age       int
	isStudent bool = true
)
        

Here I have assigned initial values for name and isStudent variables but age doesn't have any value. You can also create variables without initializing any of them.

With Type Inference:

          var (
	name      = "John"
	age       = 25
	isStudent = true
)
        

When you don't specify the types in the block, compiler will infer their types based on the initial values.


Constant Variable in Golang

In Go, a constant variable is a type of variable whose value cannot be changed once it is assigned. Constants are useful when you have values that remain constant throughout the execution of your program.

To declare a constant variable in Go, we use the const keyword followed by the variable name, the type (optional, as it can be inferred), and the assigned value.

          const PI = 3.14159
        

In this case, we declare a constant variable called PI and assign it the value 3.14159. The type of PI is automatically inferred as float64 based on the assigned value.

You can also declare multiple constants in a single declaration using a block.

          const (
    MaxRetryAttempts = 3
    TimeoutSeconds   = 30
)
        

In this example, we declare two constants: maxRetryAttempts with a value of 3 and timeoutSeconds with a value of 30.

Also Read: Mastering Constant in Golang: Declare and Use It Like a Pro


Variable Scope in Golang

Variable scope refers to the portion of your code where a variable is visible and can be accessed. Understanding variable scope is crucial for writing clean and bug-free programs.

When you declare a variable within a block (inside a function, if, for, while or switch) in Golang, that variable is only accessible within that block or any nested blocks.

          package main

import "fmt"

var globalVariable = "I am a global variable" // Global variable

func main() {
    var outerVariable = "I am an outer variable" // Outer variable within the main function

    fmt.Println(outerVariable) // Accessing the outer variable within the main function
    fmt.Println(globalVariable) // Accessing the global variable within the main function

    if true {
        var innerVariable = "I am an inner variable" // Inner variable within the if block

        fmt.Println(innerVariable)      // Accessing the inner variable within the if block
        fmt.Println(outerVariable)      // Accessing the outer variable within the if block
        fmt.Println(globalVariable)     // Accessing the global variable within the if block
    }

    // fmt.Println(innerVariable)    // This would result in a compilation error, as the inner variable is not accessible outside the if block
}

func someFunction() {
    fmt.Println(globalVariable) // Accessing the global variable within a different function
}

        

In this example, we have multiple levels of variable scope:

  • Global Scope: The globalVariable is declared outside of any function and has global scope. It can be accessed from anywhere within the package.
  • Main Function Scope: Within the main function, we have the outerVariable, which is declared and accessible within the main function. Here you can also access globalVariable.
  • If Block Scope: Inside the main function, we have an if block. Within this if block, we declare the innerVariable, which is accessible only within the if block. You also have access to both the outerVariable and the globalVariable within its scope.

Variable names must be unique within their scope. If you declare a variable with the same name in an inner scope as one in an outer scope, the inner variable will "shadow" the outer one, meaning it will take precedence and be used within that inner scope.

Understanding variable scope in multiple levels, including if blocks, help you write more organized and modular code. It prevents naming conflicts, improves code readability, and enhances the maintainability of your programs.


Naming Conventions for Golang Variables

In Go, there are certain naming conventions and guidelines that are commonly followed for naming variables. These conventions are not enforced by the language itself, rather we follow them to improve the readability and maintainability of our code.

Here are some commonly accepted naming conventions for variables in Go:

  • A variable name can't start with a number and can't contain any spaces.
  • Variable names in Go are typically written in camelCase, where the first letter of the variable name is lowercase and each subsequent word within the name is capitalized. For example: userName, totalAmount, isActivated.
  • Variable names are case-sensitive. For example: name, Name, and NAME are different variables.
  • Variables that start with an uppercase letter are considered "exported" variables. These variables are visible and accessible by other packages.
  • Try to choose descriptive names that accurately reflect the purpose and meaning of the variable.
  • Maintain consistency in your naming conventions throughout your codebase. Use the same naming style for variables across your project to ensure readability and consistency.

These are some of the important guidelines you should follow while naming your variables in Golang. The goal of these rules is to make your code readable, maintainable, and understandable by yourself and others who may be working with your code.


Conclusion

We explored various methods such as declaring variables using the var keyword, shorthand declaration with the := sign, and declaring constants.

Understanding the different ways to create variables in Go is essential for effective programming. We also discussed the variable scope and the importance of following naming conventions for variables.

By utilizing techniques such as variable declaration, type inference, and scoping rules, you can control the visibility and accessibility of variables within your programs.

Related Posts