avatarkerstan

Summarize

What is the purpose of the empty structure struct{} in Go — Code Thursday

Subscribed to: https://medium.com/@kerstan

Hi guys, I am Kerstan. Today is Code Thursday.

I will share you What is the purpose of the empty structure struct{} in Go.

So, let’s get started.

Image generated with PaintingForYou

1. Intro

We often encounter the use of the empty struct `struct{}` in project codes, and there must be a rationale underneath its usage. So what exactly is its purpose, and in what situations should it be utilized?

2. Purpose

Given that the empty structure does not occupy any memory space, it’s broadly utilized as a placeholder in numerous contexts. The prime advantage of this is resource conservation. Furthermore, the empty structure bears a potent semantic significance, implying that no value is necessary here; its sole function is to serve as a placeholder.

3. Usage Cases

a. Implementing Set Types

The Go language inherently lacks a ‘Set’ type, which is usually substitutes with a ‘Map’. However, this presents an issue while using the ‘Set’ type, only the key is needed, dispensing with the need for the value. If the value is represented by a ‘bool’, it would technically consume a byte of space. For the purpose of conserving space, this is where the functionality of the empty structure becomes aptly significant.

type Set map[int]struct{}

func main() {
  s := make(Set)
  s.add(1)
  s.add(2)
  s.add(3)
  s.remove(2)
  fmt.Println(s.exist(1))
  fmt.Println(s)

  //output:
  //true
  //map[1:{} 3:{}]
}
func (s Set) add(num int) {
  s[num] = struct{}{}
}
func (s Set) remove(num int) {
  delete(s, num)
}
func (s Set) exist(num int) bool {
  _, ok := s[num]
  return ok
}

The empty structure, functioning as a placeholder, does not impose any additional memory overhead. Hence, it conveniently addresses the issue.

b. Implementing Empty Channels

In the applications of Go’s channels, notification channels are frequently encountered. These channels do not require any data transmission but are utilized for coordinating Goroutine operations, managing various state transitions, or controlling concurrent scenarios.

Such conditions are especially apt for the deployment of empty structures, which simply serve as placeholders, without squandering memory space.

func main() {
  ch := make(chan struct{})
  go worker(ch)

  // Send a message to a worker.
  ch <- struct{}{}

  // Receive a message from the worker.
  <-ch
  println("AAA")

  //output:
  //BBB
  //AAA
}

func worker(ch chan struct{}) {
  // Receive a message from the main program.
  <-ch
  println("BBB")

  // Send a message to the main program.
  close(ch)
}

Since this channel utilizes an empty structure, it doesn’t impose any additional memory overhead.

c. Implementing Method Receivers

Employing variables of the struct type as method receivers, there are instances when the struct might not encompass any field attributes. In such cases, int or string can be used as replacements. However, considering that they consume memory space, persisting with empty structs appears more suitable.

Moreover, this approach facilitates the addition of common fields to this type in the future, making it easy to expand and maintain.

type T struct{}

func methodUse() {
  t := T{}
  t.Print()
  t.Print2()

  //output:
  //Print
  //Print2
}

func (t T) Print() {
  fmt.Println("Print")
}
func (t T) Print2() {
  fmt.Println("Print2")
}

Summary

We carried out a detailed explanation of the role and application scenarios of empty structures. In future project development processes, should we only require a placeholder without any actual significance, then it would be advisable to use empty structures. Doing so can significantly lessen unnecessary memory expenditure.

If this writing has been helpful to you, please consider giving it a clap and following. Thanks bro.

Alternatively, you can just buy me a coffee here, any sort of support is much appreciated. Enjoy your reading.

If you want to learn more knowledge about Code Thursday, please be sure to take a look at my latest articles.

What is the purpose of the empty structure struct{} in Go — Code Thursday

10 Questions to Understand the Concept of Cloud Computing — Code Thursday

Make Your Blind SQLi Faster — Code Thursday

6 Quick Discover Bug Search Syntax In Code-base

Security Issues for the Go Web — Code Thursday

Technology
Programming
Go
Development
Golang
Recommended from ReadMedium