Go Basics
Let's understand the basics of Go with some examples.
We'll cover the following
Let’s reinforce our knowledge about Go by covering some of its features.
Types
Go provides us with a number of basic data types, similar to other high-level languages. Let’s look at them in more detail.
Basic
The basic data types are numbers, strings, and booleans. In Go, they’re represented with the following types: bool
, string
, int
, int32
, uint
, uint32
, float
, and float64,
among others. Each type will have its own zero value:
false
forbool
0
for integers""
forstring
If we define a variable without specifying an initial value, the zero value will be used for the initialization.
Pointers
A pointer is a variable that’s used to hold the memory address of another variable. A pointer can be set to nil
. There are two operators involved in pointers:
*
has two meanings. The first is to declare a pointer variable, such as invar intPtr
* int
, and the second is to get the associated value of that pointer variable, such as in the check*intPtr == 3
. The latter is known as dereferencing or indirecting.&
(aka address operator) returns the address of memory of a variable in hexadecimal format. Example values are0x414020
,0x553787
, and so on.
Structs
If we have to store a bunch of related information, we need to use structs. With structs, we can describe the attributes of an entity that is part of our software. An example could be the car
entity, which can have color
, fuel
, numberOfSeats
, “maxSpeed
,” and so on as its attributes.
Collections
Go provides a few ways to store collections of items. These are:
- Array: This is a numbered sequence of elements of the same type. It has a fixed capacity, so after it’s initialized, we can’t resize it. It’s a value-type, which means that it’s passed as a copy to functions.
- Slice: This is a view of an underlying array. It can be the whole array or only a part of it. A slice has a dynamic length, which means that we can add other items to it up to its capacity. Slices are a reference-type, which means that only a reference to the slice is passed instead of all the values when passed to a function.
- Map: This is a key-value store. A key can be any comparable type, such as int or string, while the value can be of any type. Please note that the key can’t be of bool type.
Put in practice
Let’s review the types we’ve seen so far with some examples.
Get hands-on with 1400+ tech skills courses.