It’s time to get to grips with Go’s composite data types. While basic types like integers and booleans are the building blocks, composite types allow you to group data together into more complex and useful structures. This tutorial will cover Go’s most important composite types: arrays, slices, maps, and structs, which are essential for any Go program.
Table of Contents
💻 Arrays and Slices
Arrays and slices are both used for storing ordered sequences of elements, but they have a crucial difference.
- Arrays: An array has a fixed size that is part of its type. The size cannot be changed after it’s created. You declare one like this:
myArray := [4]int{1, 2, 3, 4}
. Because of their fixed size, arrays are less flexible and less commonly used directly in Go. - Slices: A slice is a more flexible, powerful view into the elements of an array. A slice does not store any data itself; it just describes a section of an underlying array. Slices have a length and a capacity and can be resized using the built-in
append
function. They are declared without a size inside the brackets:aSlice := []int{2, 4, 5}
. Slices are one of the most important data types in Go.
💻 Maps
A map is Go’s equivalent of a hash table or dictionary. It’s an unordered collection of key-value pairs. Maps are incredibly useful for storing and retrieving data where you need to look up a value by a specific key.
// Create a map using make
aMap := make(map[string]int)
// Assign key-value pairs
aMap["Mon"] = 0
aMap["Tue"] = 1
You can check if a key exists and retrieve its value in a single statement: val, ok := aMap["Tue"]
. Here, `ok` will be a boolean indicating if the key was found.
💻 Structs
A struct is a composite type that groups together fields of data. It’s useful for creating custom data structures that represent a real-world entity, like a point in a coordinate system.
type Point struct {
X int
Y int
Label string
}
You can then create an instance (a variable) of this new type: p1 := Point{X: 23, Y: 12, Label: "A Point"}
. You access the fields using dot notation, such as p1.X
.
More Topics
- Redis Guide: The High-Speed In-Memory Data Store
- Riak NoSQL Guide: What’s the Big Deal?
- MongoDB Guide: Build a Blog with Python and Bottle
- MongoDB Guide: An Admin’s Guide to Maximum Power
- MongoDB Guide: Using Native Drivers with Python and Ruby
- MariaDB Guide: The Open Source MySQL Alternative
- SQLite3 Guide: Getting Started with Python