Sobes.tech
Junior — Middle

What can the value in a map be used for if only keys are important?

sobes.tech AI

Answer from AI

In Go, if only the keys in a map are important, the 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 if a key exists
if _, exists := set["apple"]; exists {
    fmt.Println("apple is in the set")
}

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

What can the value in a map be used for if only keys… - sobes.tech