Sobes.tech
Junior — Middle

Kuidas saab Map-iga töötada, kui kasutatakse ainult võtmeid, ilma väärtusi salvestamata?

sobes.tech AI

Vastus AI-lt

In Go, if you need to use a Map only for storing keys without values, it is common to use a Map with the value type struct{} — an empty structure that does not occupy memory.

Example:

keys := make(map[string]struct{})

// Adding a key
keys["key1"] = struct{}{}

// Checking if a key exists
if _, exists := keys["key1"]; exists {
    fmt.Println("Key found")
}

// Deleting a key
delete(keys, "key1")

This approach is efficient and often used for implementing sets in Go.