关于Golang struct{}{}用法和注意事项

引自ljq@GitHub

  • struct {}
    struct {}是一个无元素的结构体类型,通常在没有信息存储时使用。
    优点:不需要内存来存储struct{}类型的值。
  • struct{}{}
    struct{}{}是一个复合字面量,它构造了一个struct{}类型的值,该值也是空。
  • 两个structt{}{}地址相等
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 {}] 

引自ljq@GitHub

你可能感兴趣的:(关于Golang struct{}{}用法和注意事项)