Home > Backend Development > Golang > Go Structs: What's the Difference Between `struct{}` and `struct{}{}?`

Go Structs: What's the Difference Between `struct{}` and `struct{}{}?`

Mary-Kate Olsen
Release: 2024-12-08 16:05:12
Original
659 people have browsed it

Go Structs: What's the Difference Between `struct{}` and `struct{}{}?`

structs in Go: struct{} and struct{}{} Demystified

In Go, struct is a powerful construct used to define data types. However, there are two special cases of structs worth examining: struct{} and struct{}.

struct{}: The Zero-Element Struct

struct{} is a struct type with no named elements. It serves a few useful purposes:

  • Zero-sized: A struct{} value does not occupy any memory, making it particularly useful for space-efficient scenarios.

Usage:

var emptyStruct struct{}
Copy after login

struct{}: Empty Composite Literal

struct{}{} is a composite literal that constructs an empty struct value. Composite literals allow for concisely initializing values of specific types. For struct{}, the syntax is simple:

var emptyStructValue = struct{}{}
Copy after login

Usage in a Set Implementation

One practical application of the empty struct is creating a set-like data structure using a Go map. Since a map only allows unique keys, we can use struct{} as the value type to create a set of unique elements without storing any values:

type Set map[string]struct{}

func main() {
    set := make(Set)
    set["foo"] = struct{}{}
    set["bar"] = struct{}{}

    _, ok := set["foo"]
    println("Is \"foo\" in the set?", ok)
}
Copy after login

Conclusion

struct{} and struct{}{} offer unique features that extend the utility of Go's struct system. The zero-element struct provides memory efficiency, while the empty composite literal assists in creating empty struct values or constructing set-like data structures.

The above is the detailed content of Go Structs: What's the Difference Between `struct{}` and `struct{}{}?`. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template