Create a Map with Custom Data Type in Golang for Data Organization

Author

Reads 475

Top view of miniature airplane placed on over gray world map with crop hand of anonymous person indicating direction representing travel concept
Credit: pexels.com, Top view of miniature airplane placed on over gray world map with crop hand of anonymous person indicating direction representing travel concept

In Go, a map is a data structure that stores key-value pairs. You can create a map with a custom data type to organize your data in a more structured way.

To define a map of custom data type in Go, you need to define a struct that represents your custom data type. As shown in the example, you can define a struct called `Person` with fields for `name`, `age`, and `city`.

A map with a custom data type can be useful when you need to store data with complex structures. For instance, you can use a map to store a collection of `Person` structs, where each key is a unique identifier and the value is a `Person` struct.

By using a map with a custom data type, you can make your code more readable and maintainable, especially when dealing with complex data structures.

Maps in Golang

In Go, maps are similar to conventional map implementations. There are three ways to define a map in Go.

You might enjoy: Golang Go

Credit: youtube.com, How to use Golang maps example | map[string]interface{} | Go

The make keyword is used to allocate memory on the heap for a map variable. It initializes the variable and puts empty/zero values where needed.

A map in Go has a set of keys and a set of values corresponding to those keys.

To use a struct as a map key, it must be comparable. This means all of its fields must be of a primitive type, a struct type with comparable fields, or a pointer to a similar type.

In Go, a map with string keys and integer values can be defined.

Related reading: Golang vs Go

Custom Datatypes

Go allows the flexibility to define and use a custom datatype based on an existing base go type, by using the keyword type. This is a great way to avoid writing tedious datatypes repeatedly.

You can define customised structures or structs and define them as a reusable datatype. To do this, you use the keyword “type” along with “struct” and define the list of attributes along with their types.

Discover more: Duckduck Go Maps

Credit: youtube.com, GoLang - Custom Data Type and Conversion

A variable of this type can be defined and initialized in three ways: by assigning values directly, by using the composite literal syntax, or by using the struct literal syntax. In this approach, the mapping of values to their corresponding attributes is bit ambiguous and depends on the sequence in which attributes occur in the original struct definition.

Maps Vs Structs

In a map, all the values are mandated to be of the same type, which is a key difference from structs.

For a map[string]string, you can only have string values, and once you define a map, the type of the key and value is fixed and can't be changed.

A map is a reference type, meaning the variable carries the address of the space in memory where the actual values reside.

You can add as many entries to a map as you like and it will be given its own serial number, which is useful for indexing.

Curious to learn more? Check out: Azure Devops Custom Work Item Type

Credit: youtube.com, Structs in C++ – Custom Data Types Explained + Live Coding Demo 💼

In contrast, a struct is a value type, where the variable itself carries the actual values assigned to it.

Once a struct is defined, you can only assign a struct instance the same number of attributes as defined in the struct definition, no more, no less.

This means you can't add or remove fields from a struct after it's been defined, unlike with maps.

Custom Datatypes

Go allows the flexibility to define and use a custom datatype based on an existing base go type, by using the keyword type.

You can define a custom datatype by using the keyword type along with struct and defining the list of attributes along with their types. No commas are needed to separate these attribute definitions.

A variable of this type can be defined and initialized in three ways: by using a single line, by using multiple lines for readability, and by using a nested syntax.

Credit: youtube.com, Custom Data Types & Classes

In Go, you can reuse these structs within other definitions as needed. For example, you can define a struct with an attribute of the same name as the struct, and Go will automatically interpret it as the struct type.

Custom datatypes can be used to add organisation and complexity to your code. This is particularly useful when you have a repeated use-case for a specific datatype.

Using Maps

You can define a map in Go using the `make` keyword, which allocates memory on the heap for a variable, usually a slice, map, or a channel. It initializes the variable and puts empty/zero values where needed.

To use a struct as a key in a map, you need to ensure that the struct is comparable. This means all its fields must be comparable, such as primitive types, struct types with comparable fields, or pointers to comparable types.

In Go, you can iterate over a map using a loop to access and operate each map key individually. This is demonstrated in an example where a struct called Address is used as a key in a map called sample.

Credit: youtube.com, Demystifying Maps in Go | How They Work and How to Use Them

A struct can be used as a key in a map if it's comparable, which means all its fields must be comparable. This allows you to use structs as keys in a map, making it a powerful tool for organizing data.

Here's a simple example of using a struct as a key in a map:

In this example, the Person, Address, and Student structs are used as keys in a map, with int values associated with each key. This is just a small sample of the many ways you can use maps in Go to organize and manipulate data.

Using a struct as a key in a map allows for more flexibility and organization of data, making it a useful tool in your programming toolkit.

Map Operations

Maps in Golang are similar to other conventional map implementations.

There are three ways to define a map in Go.

To update the value of a key in a map, you can use the assignment operator. For example, map[key] = value.

To delete a key-value pair from a map, you can use the delete function.

Iterating Over a Map

Credit: youtube.com, Golang maps | Iterating over a Map | Golang Tutorial for Beginners

Iterating over a map is a fundamental operation in programming. You can use a loop to access and operate each map key individually.

You can define a struct as a key in a map, as shown in the example with the Address struct. This struct has fields for a person's name, city, and pin code.

To iterate through a map, you can use a loop to access each key and its associated value. This is demonstrated in the example with the sample map, where each Address key is associated with an integer value.

You can access a specific field of each struct key when iterating through the map. For instance, the Name field can be accessed in the example with the Address struct.

A map can also be created with custom keys, such as the Student struct used in another example. This struct has fields for Name, RollNo, and Course.

Removing a Key from a Map

Credit: youtube.com, delete key in map

You can delete a specific key-value pair from a map using the delete function.

The delete function allows you to remove a key-value pair from a map, leaving the remaining entries intact.

The remaining map after deletion can be printed by iterating through the map and displaying the Name, RollNo, and the associated integer value.

For example, the program deletes a specific key-value pair (a4) from the map and prints the remaining elements in the map.

The key-value pair to be deleted must be specified in the delete function for the removal to be successful.

Benefits and Use Cases

Defining a map of a custom data type in Go offers numerous benefits. Generality is one of the key advantages, allowing your CustomMap to work with any comparable key type and any value type.

This generality makes your CustomMap structure reusable across various data types. You can use the same CustomMap structure for different data types, promoting code reusability.

Credit: youtube.com, Go Composite Types (Map, Struct) , Print Struct Variants | Golang 101 Tutorial

With generics in Go, you can ensure type safety by applying type constraints. This prevents you from accidentally using incompatible types for keys or values.

Here are the benefits of defining a map of a custom data type in Go:

Rosemary Boyer

Writer

Rosemary Boyer is a skilled writer with a passion for crafting engaging and informative content. With a focus on technical and educational topics, she has established herself as a reliable voice in the industry. Her writing has been featured in a variety of publications, covering subjects such as CSS Precedence, where she breaks down complex concepts into clear and concise language.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.