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.

I've learnt that it is also possible to use

map[MyType]struct{}

Any benefits of using the empty struct versus interface{}.

up vote 24 down vote accepted

Memory usage. For example, types struct{}, interface{}, and bool,

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    var s struct{}
    fmt.Println(unsafe.Sizeof(s))
    var i interface{}
    fmt.Println(unsafe.Sizeof(i))
    var b bool
    fmt.Println(unsafe.Sizeof(b))
}

Output (bytes for 32-bit architecture):

0
8
1

Output (bytes for 64-bit architecture):

0
16
1

References:

Go Data Structures: Interfaces

  • How does this affect the memory usage of the map? What will it allocate internally for a struct{} type for the values? – Daniel Williams Mar 31 '14 at 20:24
  • @DanielWilliams: A Go map stores key and element values. A struct{} element value occupies zero bytes. – peterSO Mar 31 '14 at 20:30
  • 1
    I guess that leads into what happens with a map[struct{}]struct{}? It would have a zero sized key and a zero sized value but you could put 1 thing it (also zero sized). – Daniel Williams Mar 31 '14 at 21:45
  • 2
    @DanielWilliams: Use type bool instead of type map. – peterSO Mar 31 '14 at 22:06

The empty struct and empty interface, though syntactically similar, are actually opposites. An empty struct holds no data; an empty interface can hold any type of value. If I see a map[MyType]struct{}, I know immediately that no values will be stored, only keys. If I see a map[MyType]interface{}, my first impression will be that it is a heterogenous collection of values. Even if I see code storing nil in it, I won't know for sure that some other piece of code doesn't store something else in it.

In other words, using struct{} makes your code much more readable. It also saves a little memory, as described in the other answer, but that is just a fringe benefit of using the right tool for the job.

  • What about map[MyType]bool? – peterSO Mar 31 '14 at 23:09
  • I would actually tend to use map[MyType]bool myself, because it can be used directly in an if condition, and it would probably produce the most readable code. But the OP only asked about struct and interface, and I wanted to keep my answer simple. (And map[MyType]struct{} is a recognized idiom for sets.) – andybalholm Apr 1 '14 at 16:17

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.