SoFunction
Updated on 2025-04-08

Golang implements composite data types

Composite Types of Go language are used to build more complex data structures by combining basic data types. Common composite data types are: arrays, slices, maps, structures and interfaces.

1. Array

Arrays are a very basic and important data structure in programming that allows us to store a series of data of the same type. Imagine an array is like a storage cabinet, each drawer can hold the same type of items, such as apples or books. Each drawer has a number, which is what we call "index". Through this index, we can easily find and remove items in any drawer.

Declaring an array requires specifying how many elements it can store, and this number is fixed throughout the life of the array.

Statement method

var arr [3]int // Declare an array containing 3 integers

When we need to access or modify an element in an array, we can achieve it through indexing. An index is a number starting from 0, which points to a specific location in the array. For example, arr[0] is the first element in the array, arr[1] is the second, and so on.

Access elements

arr[0] = 10 // Access the first element of the array

characteristic: The array size is part of the type, so two arrays of different sizes are considered different types.

It is worth noting that arrays are considered as value types in programming. This means that when we assign an array to another variable, or pass it as an argument to a function, we are actually copying the data of the entire array. This is different from a reference type, which passes the address of the data, while an array is a real copy of the data. This copying behavior ensures the security of the array data, because modifications to the replicas do not affect the original array, thus avoiding unexpected data changes.

2. Slice

In Go, slices are a very powerful data structure that is based on arrays but provides more flexibility. You can think of slices as a "dynamic view" of an array, which allows us to process data collections in a more flexible way.

Unlike arrays, the length of the slice is dynamic, meaning it can grow or shrink as needed. A slice actually contains three important information: a pointer to the underlying array, the length of the slice (the number of elements the current slice contains), and the capacity of the slice (the maximum length the slice can be expanded to without causing the underlying array to be reassigned). These three properties make slices both efficient and convenient when processing large amounts of data.

When declaring a slice, we don't need to specify its length, which is in sharp contrast to how the array is declared.

Statement method

var slice []int // Declare an integer slice

A key feature of slices is the support for append operations, which allows us to easily add new elements to the slice. When we use the append function, if the slice is not enough to accommodate new elements, Go will automatically assign us a new, larger array, copy the elements from the old array to the new array, and then add new elements.

Create slices

slice = append(slice, 1, 2, 3) // Add elements using append

characteristic: Slices can expand and shrink dynamically as the program runs.

Furthermore, slices are reference types, which means that when we assign a slice or pass it as an argument to a function, we are actually copying the reference of the slice, rather than copying the entire underlying array. This way of referential passes makes slices very efficient when passing between functions because we don't need to copy large amounts of data. At the same time, this also means that any modification to the slice will affect the original slice because they point to the same underlying array.

3. Map (Map)

Map is a very practical data structure that allows us to store data in the form of key-value pairs. You can think of a mapping as a phone book where each name (key) corresponds to a phone number (value). This structure allows us to quickly find phone numbers based on names without having to browse the entire phone book.

When we want to create a map in Go, we need to specify the types of keys and values ​​explicitly.

Statement method

var m map[string]int // Declare a map where a key is a string and a value is an int

Initialize the map

m = make(map[string]int)

Maps are reference types in Go, meaning they do not store data directly like arrays or slices, but rather references to the data. Each map has a dynamic data structure associated with it, which is unique and is responsible for storing all key-value pairs. This design makes mappings very efficient in memory usage and performance, as they can grow or shrink dynamically as needed.

Accessing elements in a map is achieved by keys, which is different from the way an array or slice accesses elements through an index.

Operation Mapping

m["age"] = 30 // Add or update elementsvalue := m["age"] // Get the valuedelete(m, "age") // Delete key-value pairs

4. Struct

A struct is a powerful aggregated data type that allows us to combine multiple different kinds of data to form a meaningful whole. It's like how we combine various ingredients into a dish, or assemble different parts into a machine. Structures allow us to organize data in a structured way, making it easier to manage and use.

When creating a structure, we need to define its fields, including the name and type of each field.

Statement method

type Person struct {
    Name string
    Age  int
}

Once we have defined the structure, our member variables can be accessed and modified by the field name.

Use structure

var p Person
 = "John"
 = 30

Initialize the structure

p := Person{Name: "John", Age: 30}

Structures are value types in Go language. This means that when we assign a value to a struct or pass it as a parameter to a function, we are actually copying the value of the entire struct instead of just copying a pointer to the struct.

5. Interface

An interface is a powerful type that defines a set of methods but does not implement them. An interface can be regarded as a set of "contracts", and any type that implements these methods automatically satisfy the interface. This design makes the interface a key tool for implementing polymorphic and code decoupling in the Go language.

The interface can be accessed by keywordsinterfaceTo define it, followed by a pair of braces {}, which lists all method signatures that the interface needs to implement.

Declare interface

type Speaker interface {
    Speak() string
}

In Go, a type automatically implements an interface if the type has all the methods declared in the interface. This implementation is implicit and does not require explicit declarations.

Implement the interface

type Person struct {
    Name string
}

func (p Person) Speak() string {
    return "Hello, my name is " + 
}

Usage interface

var s Speaker
s = Person{Name: "John"}
(()) // Call interface method

Summarize:

Go's composite data types provide a variety of ways to build complex data structures. Arrays and slices are suitable for processing collection data, maps are used to store key-value pairs, structures are used to organize different types of data together, and interfaces provide flexible polymorphic capabilities. These composite data types are the powerful and flexible foundation of Go.

This is the end of this article about Golang's implementation of compound data types. For more related Golang's compound data types, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!