How to convert a slice to a map in Golang?

To convert a slice to a map in Golang, you can follow these steps:

  1. Create an empty map using the make() function.
  2. Iterate through the slice using a for loop.
  3. Assign each element of the slice as a key in the map, and set its corresponding value to true (or any desired value).

Here's an example:

package main import "fmt" func main() { // Sample slice slice := []string{"apple", "banana", "cherry"} // Convert slice to map myMap := make(map[string]bool) for _, value := range slice { myMap[value] = true } // Print the map fmt.Println(myMap) }

In this example, the slice contains strings. Each string element of the slice is assigned as a key in the map, and the value is set to true. The final result will be a map with the slice elements as keys. Output:

map[apple:true banana:true cherry:true]