About the usage and precautions of Golang struct{}{}

See more ljq@GitHub

  • struct {}
    struct {} is a structure type with no elements, usually used when there is no information storage.
    Advantages: No memory is needed to store values ​​of type struct{}.
  • struct{}{}
    struct{}{} is a compound literal, which constructs a value of struct{} type, which is also empty.
  • Two structt{}{} addresses are equal
package main

import "fmt"

type idBval struct {
Id int
}

func main() {
idA := struct{}{}
fmt.Printf("idA: %T and %v \n\n", idA, idA)

idB := idBval{
		1,
}
idB.Id = 2
fmt.Printf("idB: %T and %v \n\n", idB, idB)

idC := struct {
Id int
}{
		1,
}
fmt.Printf("idC: %T and %v \n\n", idC, idC)

mapD := make(map[string]struct{})
mapD["mapD"] = struct{}{}
_, ok := mapD["mapD"]
fmt.Printf("mapD['mapD'] is %v \n\n", ok)

sliceE := make([]interface{}, 2)
sliceE[0] = 1
sliceE[1] = struct{}{}
fmt.Printf("idE: %T and %v \n\n", sliceE, sliceE)

}

Output:


idA: struct {} and {}

idB: main.idBval and {2}

idC: struct {Id int} and {1}

mapD['mapD'] is true

idE: []interface {} and [1 {}]

See more ljq@GitHub