Golang: Converting slice into a map

Akarsh Seggemu
4 min readMar 14, 2024
Using Golang you need to convert a given slice to a map object.

How to do that conversion?

because slices only contain one element in them but a map object consists of a key and value pair. This is the first question you in order to have a successful conversion from slice to a map object.

In my case, I need to store the slice elements as keys in the map object. For the value I have a constraint that the sum of all element from slice should be equal to 100.

I have come up with the following solution in an algorithmic expression.

Step 1: Start
Step 2: Define the main function.
Step 2.1: Create a slice named slice containing strings "A", "B", "C", and "D".
Step 2.2: Call the function convertSliceToMap with the slice as input, storing the result in a variable named result.
Step 2.3: Iterate over the key-value pairs in the result map.
Step 2.3.1: Print the key and value with two decimal places.
Step 3: Define the function convertSliceToMap, taking a slice of strings named items as input and returning a map[string]float64.
Step 3.1: Initialize an empty map named result of type map[string]float64.
Step 3.2: Calculate the number of items in the slice and store it in numberOfItems as a float64.
Step 3.3: Initialize a variable totalPrice to 100 as a float64.
Step 3.4: Calculate the valueForEachItem by dividing totalPrice by numberOfItems.
Step 3.5: Iterate over each item in the items slice.
Step 3.5.1: Assign the valueForEachItem to the result map with the item as the key.
Step 3.6: Return the result map.
Step 4: End

From the algorithmic expression I created the Golang code.

First, I defined a function convertSliceToMap . This function takes a slice of strings as input and returns a map where each string from the slice is a key and the value is the result of dividing 100 by the number of items in the slice. It starts by creating an empty map and calculating the value for each item. It then iterates over the slice, adding each string and its corresponding value to the map.

Run the code main.go

package main

import "fmt"

func main() {
slice := []string{"A", "B", "C", "D"}
result := convertSliceToMap(slice)
for key, value := range result {
fmt.Printf("%s: %.2f\n", key, value)
}
}

func convertSliceToMap(items []string) map[string]float64 {
result := make(map[string]float64)
numberOfItems := float64(len(items))
totalPrice := float64(100)
valueForEachItem := float64(totalPrice / numberOfItems)
for _, item := range items {
result[item] = valueForEachItem
}
return result
}

Output:

A: 25.00
B: 25.00
C: 25.00
D: 25.00

Unit Test the code from main.go by using main_test.go

package main

import (
"reflect"
"testing"
)

func TestConvertSliceToMap(t *testing.T) {
slice := []string{"A", "B", "C", "D"}
expected := map[string]float64{
"A": 25.00,
"B": 25.00,
"C": 25.00,
"D": 25.00,
}

result := convertSliceToMap(slice)

if !reflect.DeepEqual(result, expected) {
t.Errorf("Expected %v, but got %v", expected, result)
}
}

Test output

After running the test you should see the following output which indicates the test is passed.

Running tool: /opt/homebrew/bin/go test -timeout 30s -run ^TestConvertSliceToMap$

=== RUN TestConvertSliceToMap
--- PASS: TestConvertSliceToMap (0.00s)
PASS
ok _/Users/akarshseggemu/Developmer/Go/ 0.100s

The unit test function TestConvertSliceToMap tests the function convertSliceToMap . It uses two functions, DeepEqual and Errorf.

  1. The DeepEqual function is a part of the reflect package in Go. It checks if two values are deeply equal, meaning their public and private fields are identical, their elements (if they are arrays or slices) are identical, and their keys and values (if they are maps) are identical. It's used in the test function to compare the result of convertSliceToMap to the expected output.
  2. The Errorf function is a method of the testing.T type. It formats its arguments according to the format specifier and writes the result to the error log. If the test is not yet marked as failed, Errorf marks it as failed. It's used in the test function to log an error if the result of convertSliceToMap is not as expected.

The test begins by defining a slice of strings as test input and the test output is defined in the variable expected. The variable expected defines a map that contains each string from the slice as a key and each has a value of 25.00. It then calls convertSliceToMap with the slice as an argument and stores the function output as variable result. The reflect.DeepEqual function is used to compare the result to the expected output. If they are not equal, it calls t.Errorf to log the error and fail the test.

I hope you enjoyed my article on converting slice into a map.

If you like my articles, please follow me on Medium, you can also watch my videos on YouTube and you can also support me by buying me a coffee.

--

--

Akarsh Seggemu

IT Team Lead | MSc in Computer Science from Technische Universität Berlin | Writing articles to Empower Software Engineers and IT Leaders