Any difference in using an empty interface or an empty struct as a map's value?

后端 未结 3 1141
南方客
南方客 2020-12-13 06:36

I am using this construct to simulate a set

type MyType uint8
map[MyType]interface{}

I then add in all my keys and map them to nil

3条回答
  •  心在旅途
    2020-12-13 07:29

    I would like to add additional detail about empty struct , as differences are already covered by andybalholm and peterSO .

    Below is the example which shows usability of empty struct .

    Creates an instance of rectangle struct by using a pointer address operator is denoted by & symbol.

    package main
    
    import "fmt"
    
    type rectangle struct {
        length  int
        breadth int
        color   string
    }
    
    func main() {
        var rect1 = &rectangle{10, 20, "Green"} // Can't skip any value
        fmt.Println(rect1)
    
        var rect2 = &rectangle{}
        rect2.length = 10
        rect2.color = "Red"
        fmt.Println(rect2) // breadth skipped
    
        var rect3 = &rectangle{}
        (*rect3).breadth = 10
        (*rect3).color = "Blue"
        fmt.Println(rect3) // length skipped
    }
    

    Reference : https://www.golangprograms.com/go-language/struct.html

    For a thorough read you can refer : https://dave.cheney.net/2014/03/25/the-empty-struct

提交回复
热议问题