Go Variables

In Go, variables act as containers for storing various types of data. By using variables, you can store values such as numbers, text, or logical states and use them throughout your program.

Tutorials dojo strip



Go Variable Types

Go supports several variable types, such as:

  • int: For storing whole numbers, like 42 or -100.
  • float32: For storing numbers with decimal points, such as 3.14 or -9.81.
  • string: For storing textual data, like "Hello Go!" (enclosed in double quotes).
  • bool: For storing logical states, which can be either true or false.

The specific data type determines how the variable behaves and what kind of data it can store. For more details, refer to the Go Data Types lesson.




Declaring Variables

In Go, variables can be declared in two main ways:

Declaring with the var Keyword

The var keyword lets you explicitly define a variable’s name, type, and optionally its value.

Syntax:

Go

You must specify either the type or the value (or both) when using var.

Declaring with the := Syntax

Go also supports shorthand variable declarations using :=. Here, the compiler determines the variable’s type based on its assigned value.

Syntax:

Go

This shorthand requires assigning a value during declaration.




Variable Declaration with Initial Values

When the value of a variable is known at the time of declaration, it can be initialized in a single step.

Example:

Go

Here:

  • brand1 is explicitly defined as a string.
  • brand2 and speed have their types inferred as string and int, respectively.




Variable Declaration without Initial Values

In Go, if you declare a variable without initializing it, the compiler assigns it a default value based on its type.

Example:

Go

In this example:

  • model defaults to an empty string "".
  • year defaults to 0.
  • active defaults to false.




Assigning Values After Declaration

You can assign a value to a variable after it has been declared.

Example:

Go

Note: Variables declared using := must have a value during their declaration.




Differences Between var and :=

There are subtle differences between var and :=:

Featurevar:=
Can be used inside and outside functionsYesNo
Can separate declaration and assignmentYesNo, must declare and assign value

Example with var Outside Functions:

Go

Example with := Outside Functions:

Go

Result:
The code produces an error because := cannot be used outside a function:

Go

Tutorials dojo strip