关于golang:关于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

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据