- Author

- Name
- Nelson Silva
- Social
Introduction
Variables are the heart of any programming language, and Go is no exception. They allow us to store, retrieve and manipulate data efficiently.
Understanding Variables
A variable is a container that stores information. In the context of programming, it can be seen as a name assigned to a space in the computer's memory.
Types of Variables
Go, being a strongly typed language, offers a variety of variable types:
- Integer: Represents numbers without a decimal point. In Go, there are several variations, such as int, int8, int16, int32 and int64, depending on the required precision.
- Decimal (float32 and float64): Used to store numbers with decimal points. The difference between float32 and float64 is the precision and the size of the memory space they occupy.
- String: Sequences of characters used to represent text.
- Boolean: Can be
trueorfalse.
In addition to these basic types, Go offers arrays, slices, maps, structs, pointers and many others that can be explored in future posts.
Variable Declaration and Initialisation
In Go, you can declare variables in several ways:
- Using the
varoperator:
var name string
name = "GoLang"
- Declaring and initialising on a single line:
var age int = 30
- Using type inference with the
:=operator:
city := "Lisbon"
Type inference is a powerful feature in Go, allowing the compiler to automatically determine the type of the variable based on the initial value.
Practical Example
package main
import "fmt"
func main() {
var integer int = 10
var _string string = "I am a string."
var noType = "I am still a string."
decimal := 10.5
boolean := true
fmt.Println("integer:", integer) // integer: 10
fmt.Println("string:", _string) // string: I am a string.
fmt.Println("no type:", noType) // no type: I am still a string.
fmt.Println("decimal:", decimal) // decimal: 10.5
fmt.Println("boolean:", boolean) // boolean: true
}
Conclusion
Variables are a pillar of programming in Go. By understanding how to declare, initialise and use variables of different types, you will be well equipped to tackle more complex challenges in Go. Strong typing combined with type inference makes Go a unique language, allowing flexibility without compromising safety or performance.