Sling Academy
Home/Golang/Building Custom Map Functions for Enhanced Usability in Go

Building Custom Map Functions for Enhanced Usability in Go

Last updated: November 24, 2024

Introduction

In Go programming, the map data structure is highly effective for managing collections of data. However, Go’s native map functions might not always cater to specific use cases, leading developers to create custom map functions for greater flexibility. This article explores how to build such functions, enhancing their usability for various scenarios.

Basics of Map in Go

Before diving into custom functions, it’s crucial to understand Go’s native map capabilities. Maps in Go associate values with keys, allowing for efficient data retrieval.

Basic Map Example

package main

import "fmt"

func main() {
    // Define a map for storing language keywords
    languageKeywords := map[string]string{
        "Go": "Golang",
        "JS": "JavaScript",
        "Py": "Python",
    }

    fmt.Println(languageKeywords)
}

Intermediate: Custom Map Functions

Now that we know the basics, let’s extend our capabilities by creating a custom map function.

Function to Add/Update Key-Value Pairs

package main

import "fmt"

// Custom function to add or update a key-value pair
func addUpdateKeyValue(m map[string]string, key string, value string) {
    m[key] = value
}

func main() {
    languageKeywords := map[string]string{
        "Go": "Golang",
        "JS": "JavaScript",
        "Py": "Python",
    }

    // Add a new key-value pair
    addUpdateKeyValue(languageKeywords, "Java", "Java Language")
    fmt.Println(languageKeywords)

    // Update an existing key-value pair
    addUpdateKeyValue(languageKeywords, "JS", "JS Language")
    fmt.Println(languageKeywords)
}

Function for Deleting Key-Value Pairs

package main

import "fmt"

// Custom function to delete a key-value pair
func deleteKeyValue(m map[string]string, key string) {
    delete(m, key)
}

func main() {
    languageKeywords := map[string]string{
        "Go": "Golang",
        "JS": "JavaScript",
        "Py": "Python",
    }

    // Delete a key-value pair
    deleteKeyValue(languageKeywords, "Py")
    fmt.Println(languageKeywords)
}

Advanced: Enhancing Map Functionality

In advanced scenarios, you might want your functions to return certain types of outputs or have more complex logic. For example, you might want a function that filters map values.

Function for Filtering Map Based on Values

package main

import "fmt"

// Custom function to filter map based on given substring
func filterBySubstring(m map[string]string, substr string) map[string]string {
    filteredMap := make(map[string]string)
    for key, value := range m {
        if contains(value, substr) {
            filteredMap[key] = value
        }
    }
    return filteredMap
}

// Helper function to check if substring is in string
func contains(s string, substr string) bool {
    return strings.Contains(s, substr)
}

func main() {
    languageKeywords := map[string]string{
        "Go": "Golang",
        "JS": "JavaScript",
        "Py": "Python",
    }

    // Filter map where values contain 'lang'
    fmt.Println(filterBySubstring(languageKeywords, "lang"))
}

Conclusion

Creating custom map functions in Go can significantly enhance the functionality and usability of your code. By understanding the fundamental operations and gradually building more advanced utilities, you can handle complex data manipulation tasks effectively.

Next Article: Partitioning Data Sets with Maps in Go

Previous Article: Using Maps with Pointers: Advanced Use Cases in Go

Series: Working with Maps in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant