Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use empty constructions in go language projects

Shulou Source: shulou.com Published: 2022-05-31 22:07:06 10月01日 Update

This article mainly introduces "how to use empty structures in go language projects". In daily operation, I believe that many people have doubts about how to use empty structures in go language projects. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use empty structures in go language projects"! Next, please follow the editor to study!

Usage: 1, when using map as a Set, the value type can be defined as an empty structure and can only be used as a placeholder; channel does not need to send data, but is only used to notify sub-programs to perform tasks, etc., empty structures can be used as placeholders; 3, structures only contain methods, and do not contain any fields, empty structures can be declared to save resources.

1. Does the empty structure occupy space?

In the Go language, we can use unsafe.Sizeof to calculate the number of bytes to be consumed by an instance of a data type.

Package mainimport ("fmt"unsafe") func main () {fmt.Println (unsafe.Sizeof (struct {} {}))}

Running the above example will output:

$go run main.go0

That is, the empty struct {} instance does not occupy any memory space.

2. The function of empty structure.

Because empty structures do not occupy memory space, they are widely used as placeholders in various scenarios. One is to save resources, and the other is that the empty structure itself has a strong semantics, that is, it does not need any value, only as a placeholder.

2.1implementation set (Set)

The Go language standard library does not provide an implementation of Set and is usually replaced by map. In fact, for collections, only map keys are needed, not values. Even if the value is set to bool, it will occupy an extra byte, so assuming that there are 1 million pieces of data in map, 1MB space will be wasted.

Therefore, when using map as a Set, you can define the value type as an empty structure and use it only as a placeholder.

Type Set map [string] struct {} func (s Set) Has (key string) bool {_, ok: = s [key] return ok} func (s Set) Add (key string) {s [key] = struct {} func (s Set) Delete (key string) {delete (s) Key)} func main () {s: = make (Set) s.Add ("Tom") s.Add ("Sam") fmt.Println (s.Has ("Tom")) fmt.Println (s.Has ("Jack"))}

2.2 Channel that does not send data (channel)

Func worker (ch chan struct {}) {

Tags: Structure language data project method space type learning memory situation appropriateness fact fact task example scenario field byte instance more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Redmi Docker OPPO Reno macOS