To convert a slice to a map in Golang, you can follow these steps:
make()
function.for
loop.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]