Topic Overview and Goal Setting

Greetings! As we venture into our Go Programming Expedition, we're setting out to understand Go Variables, our essential assistants. Similar to coordinates on a map, variables guide our code, endowing it with data and meaning.

In simple terms, a variable in coding is akin to a ticket — a reserved place in memory where a value can be stored. This lesson aims to demystify the concept of Go variables, examining their definition, naming conventions, assignment operations, and the concept of constant variables.

What are Go Variables?

Think of Go variables as tickets, each carrying specific data. The following short example illustrates how a variable is defined in Go:

var numOfMountainPeaks int // We declare a variable, similar to buying a ticket
numOfMountainPeaks = 14 // We then assign it a value
fmt.Println(numOfMountainPeaks) // Finally, we validate its contents. It outputs: 14

Here, int is the data type of the variable (integer), numOfMountainPeaks is the variable's name, and 14 is its value. We will delve deeper into data types in the upcoming lesson, so don't fret if the int part is somewhat unclear now.

Alternatively, you can declare and assign the variable in one step like this:

var numOfMountainPeaks = 14 // declaring and assigning the variable at once
fmt.Println(numOfMountainPeaks)

Or using a short declaration:

numOfMountainPeaks := 14 // creating and assigning the variable with shorthand
fmt.Println(numOfMountainPeaks)

To sum up, here are all the ways to initialize a variable:

  • Declaring without initializing: var name int;
  • Declaring and Initializing: var name = 5;
  • Short Declaring and Initializing: name := 5;
Go Naming Conventions

Just as with correctly labeling a ticket, naming a Go variable requires adherence to certain rules and conventions. These assist us in keeping our code error-free and easily interpreted by others.

Go's variable name rules follow the CamelCase convention: If the variable name contains a single word, all letters should be lowercase. If the variable name comprises multiple words, the first one should be lowercase, and each subsequent one should start with a capital letter. For example, age, weight, myAge, firstDayOfWeek.

Special characters and digits are not permitted at the start of variable names.

// Correct variable naming
var myWeight int = 72
var district9Population int = 10000
myAge := 20

// Incorrect variable naming (commented intentionally)
// var 0zero = 0;
// var ?questionMark = 1;
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal