乐趣区

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

退出移动版