6

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

 2 years ago
source link: https://studygolang.com/articles/35190
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

ljq · 2天之前 · 271 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    

引自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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK