Sobes.tech
Junior — Middle

What is the main purpose of an empty data structure?

sobes.tech AI

Answer from AI

An empty struct in Go (struct{}) contains no fields and occupies 0 bytes of memory. Its main purpose is to serve as a marker or flag when the presence of a value is important, rather than its content. For example, it is often used as a value in a map to implement a set, where keys are the set elements and values are empty structs to save memory.

Example of using an empty struct for a set:

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

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

Thus, an empty struct helps efficiently represent collections without duplicate data.