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.
Think of Go variables as tickets, each carrying specific data. The following short example illustrates how a variable is defined in Go:
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:
Or using a short declaration:
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
;
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.
Assigning in Go involves allocating or updating a variable's value using the =
operator. This act is analogous to stamping a ticket.
While the previous section describes how to change a variable's value, Go also provides a method to define constants — variables that cannot alter their value once assigned. We use the const
keyword to declare a constant. Constants are generally named using uppercase letters, and words are separated by underscores _
.
Declaring a value as const
is a common practice when you know it won't change, thereby enhancing readability, providing safety (avoiding accidental changes), and sometimes improving performance reasons.
Here, DAYS_IN_WEEK
serves as a constant, disallowing adjustments once assigned. The value for this variable cannot be changed after its assignment.
Great job! You've now gained insights into the basics of variables and constants in Go. In our upcoming lessons, we'll apply these concepts through practical exercises. Practicing is indeed crucial for transforming knowledge into skill, so let's delve into the tasks and continue our Go Programming Expedition!
