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

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

DDD
DDDOriginal
2024-12-11 05:28:13290browse

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

Delving into the Nature of struct{} and struct{}{} in Go

Go leverages the concept of structs to define sequences of named elements. While struct{} and struct{}{} may seem similar, they possess subtle distinctions.

struct{}: The Zero-Sized Empty Struct

A struct{} represents a struct with no defined elements. It exists primarily to hold no data. Its diminutive size enables efficient memory utilization without requiring additional space.

struct{}: A Composite Literal for the Empty Struct

In contrast, struct{}{} constructs a value of type struct{}. Its syntax features the struct type followed by empty braces, as no fields exist.

Leveraging struct{} in Practice: Creating a Set

Go inherently lacks a set data structure, but maps offer a viable alternative. By defining a map's value type as struct{}, we create a set analogue that stores only keys. This technique maintains the unicity of keys within the map.

For instance:

var set map[string]struct{}
set = make(map[string]struct{})
set["red"] = struct{}{}
set["blue"] = struct{}{}
_, ok := set["red"]
fmt.Println("Is red in the map?", ok)

The map functionality showcases the presence or absence of keys, mimicking set behavior.

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

Statement:
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