Sobes.tech
Junior — Middle

Milleks võib väärtust kasutada kaardil, kui olulised on ainult võtmed?

sobes.tech AI

Vastus AI-lt

In Go, if only the keys in a map are important, the value (value) can be used as an empty struct struct{}. This helps save memory, as an empty struct occupies no space. This approach is often used to implement sets, where only the presence of a key matters.

Example:

set := make(map[string]struct{})
set["apple"] = struct{}{}
set["banana"] = struct{}{}

// Check for key existence
if _, exists := set["apple"]; exists {
    fmt.Println("apple is in the set")
}

Thus, the value simply acts as a marker for the presence of the key without additional memory overhead.